Skip to content

Beginner Tips: Threading in Xojo

Many times, when we create a desktop application which is doing huge processes, it happens that the responsiveness of our app can be interrupted for few seconds. As developers we need to avoid such scenarios because we want to keep the interaction between the user and the app constant while it’s in use. You have to imagine that our customer doesn’t have a developer’s mindset and will not wait more than 5 seconds if the app freezes.

Threading is a great solution to these situations. Threading ensures that the code of operations with long working duration keeps doing its job while acting on the UI still possible: it could be clicking on some buttons, writing some text in a textfield or even opening a file dialogue. 

Typically we also need to think about a way to show users that something is working in the background. A common way to do this is filling a progress bar. Or maybe changing the text of a label that shows the current status. Of course, there are other possibilities depending of the creativity of the developer. 

As we know, using multiple threads allows running a few tasks on the same program. In Xojo, your code runs in default on the main thread. So if you want to run other code in a second thread, you need to drag and drop the thread class to your project just like any other class from the library to create a new instance of it. 

There you have two events: The Run event helps to run the task which could take some time to finish. The UserInterfaceUpdate event is like the name says, responsible for any change on the users interface. Both events work hand in hand since for any update we usually need some values delivered from our code under the run Event. The connecting point between both events is the method AddUserInterfaceUpdate. It helps us to prepare key:value pairs which we could need for any sort of interaction with a user or with our self when we catch exceptions.

The Event UserInterfaceUpdate receives all those pairs as an array of dictionaries. It makes looping over the data and fetching the desired value with the right key much simpler and adaptable to any kind of logic. 

Watch this video to watch me implement a thread to output to a log file:

Now I hope you have a basic understanding of how threads work in Xojo and how they could be useful for your projects in the future.

Mohamed Braham is 34 years old and works as an IT Developer. He specializes in developing desktop applications with Xojo and solving issues in the commercial field. Originally an automotive engineer with many years experience of industrial projects, he discovered a passion for programming in 2020 and is self-taught. In his freetime he likes making videos on his YouTube Channel: Braham Creation 2 go where he publishes tutorial videos about Xojo. As a self-taught programmer, he values finding good help online for free and wants to give a little back and share his knowledge with the Xojo community.