How to call a method from a thread?


Thread1 is a control in Window1.
Using a pushbutton, Thread1.Start works.
Thread1.Run() works fine with a progress bar.
Now I want Tread1.Run() to call a method, Method1.
Xojo launches but then gives ThreadAccessingUIException at the call to Method1.

  1. How do I define a method that can be called from Thread1?

  2. How do I move Thread1 out of Window1 into standard Module1, so that Thread1 is independent of Window1? My intention is to launch multiple threads in a Xojo app that processes in background with no windows.

Any advice welcome :smiley:

There is nothing wrong is calling methods from a thread. In fact, under my Thread.Run Event is a method.

The only thing you cannot do is to update, read or write anything on the UI from a thread directly. The ThreadAccessingUIException shows your method is doing that.

If you need to get some properties from the UI, copy them into a global property and read off from there. It can be a string array, an integer, boolean or string.

One method is laid out in Updating the User Interface with the New Thread Class – Xojo Programming Blog

Before that, what we did was to use a timer. Within your method, increment a property which contains the value you want to update in the UI then use the timer to do the update.

Nothing in your thread is allowed to access the user interface (such as changing something in a window). You should look at the thread documentation and learn about the AddUSerInterfaceUpdate() method and the UserInterfaceUpdate event.

Thanks, Edwin and Tim.
Problem 1. was because Method1 output a MessageBox :frowning:
Now Method1 can be called from both the main line and the thread without error.
Yes, am using AddUSerInterfaceUpdate() method and the UserInterfaceUpdate event to update a listbox and progress bar as described in an old Forum thread. Thank you, author of that post. It seems to work fine without a timer.

Create a new class in your project and set its Super’s value to “Thread”. That works on Console apps too, if you really don’t need any UI.

1 Like

Worth remembering that the threads are cooperative and will only use a single CPU core.

Thanks, Arnaud. I also got this to work in code:
var t as new Thread
Addhandler, AddressOf threadCode

Ian, oh no!

If you use AddHandler remember to remove the handler before the instance is destroyed otherwise you will get a leak.

Just worth a note: this works specifically for threads because Xojo keeps an internal list of them. Should it be other objects, like a shell, it would vanish at the end of that method because the variable (the only reference to it) would go out of scope.