Task

From Xojo Documentation

Class (inherits from Thread)

Task is a Thread subclass that has a mechanism for allow user interface updates. Task is not part of the Xojo Framework.

Events
Run UpdateUI UserInterfaceUpdate
Properties
DebugIdentifier StackSize ThreadState
Priority ThreadID fa-lock-32.png
Methods
AddUserInterfaceUpdate Sleep UpdateUI
Pause Start
Resume Stop

Notes

Task is not part of the Xojo framework, but because UI access from a thread raises a ThreadAccessingUIException, it is important enough to warrant its own entry in the Language Reference.

You can get the Task class (and its related TaskEvent class) in this example project included with Xojo: Examples/Desktop/UpdatingUIFromThread/UIThreadingWithTask

If you instantiate a Task in a local variable, keep in mind that the Task instance only remains available as long as both the variable is in scope and the thread is running. If the variable goes out of scope then it is possible the thread will complete but not be able to process its UpdateUI event because it is no longer available. To avoid this you should instead create your instance as a property so that it remains available longer or add a Sleep call of sufficient time to the end of the thread so that the UpdateUI event has enough time to run.

Example

To use Task, add both TaskEvent and Task to your project and then drag Task onto a Layout Editor.

In the UpdateUI event handler, you add put the code that accessing the UI. This code updates a ProgressBar (called UIProgress) on a Window:

If args.HasKey("UIProgress") Then
UIProgress.Value = args.Value("UIProgress").IntegerValue
End If

The args parameter is a Dictionary containing information supplied by the UpdateUI method that can be used to update the UI.

The Run method contains the code that runs in the thread and calls UpdateUI with any necessary information:

Dim progressValue As Integer

While progressValue < 100
progressValue = progressValue + 1

// Do nothing for 1/4 second or so so folks can see the actual progress
Dim waitUntil As Integer = Ticks + 15

While Ticks < waitUntil
Wend

// Call UpdateUI with any parameters you need. This calls the UpdateUI event handler
// where you can directly access any UI controls on the Window.

// This specifies simple parameters using a Pair
// You can also pass values using a Dictionary
Me.UpdateUI("UIProgress":progressValue)

Wend

See Also

Thread