« Tip of day: Animated … | Home | Xojo Pricings: Beware… »

The Cancel problem with Threads

We love to use threads in Real Studio & Xojo. Especially if we can use plugins to offload work to preemptive threads in order to get more CPU cores busy. The MBS Plugin has a couple of MT methods which do that. Now while getting 8 cores busy or simply no beach ball in the GUI with network operations, there is a problem we have to face: Cancelling.

The problem with canceling a thread is that you have to code your threads to be cancelable and do that if needed. So if your user wants to quit the app while you do something, the user will not like if your app ignores the quit or you take 5 minutes to finish your work before you really quit. When your app quits with running threads, the runtime will call the Kill method on the thread object to stop the thread. The Kill method as far as we know injects an ThreadEndException into the thread which causes normal code to return quickly and terminate the thread. Now that exception handling is not working well while inside a plugin function. Currently there seems to be no way to ask the runtime if there is a pending exception. The last days we looked into this as we got a lot of crashes with ThreadKill function: Feedback case 26915.

A way to solve those crashes is to cancel our threads on our own. So if while a long operation the user presses some cancel button or the app closes, you may want to cancel threads before the runtime tries to kill them. So for example in a work window we have code in close event where we loop through threads and tell them to cancel. For CURLSMBS class we recently added a cancel property for that. It will tell PerformMT & Perform method to return quickly. Than we loop and check threads to wait for them to finish. Those threads of course need to be cancel aware and also detect this state and delete temporary files for example.

With threads and avoiding crashes we also want to not access any GUI. Querying window or control properties can cause trouble as well as updating them. So for us we simply store current progress in properties of the thread. We also put a boolean flag there so we know if new status information is available. Now a timer on the progress window can check regularly and update the GUI on the main thread.

On our plugin examples, we have around 100 projects using threads and we will to revise them over time. If you see a problem, please query us for an updated project. Next prerelease plugins already includes an updated threaded download sample for CURL. The biggest plugin in space...
30 05 13 - 17:29