Accessing the UI thread
A Dispatcher provides services for managing work items on a specific thread. In Avalonia you will usually have only one Dispatcher, the one that handles the UI thread. Whenever you need to update the UI from a different thread than the UI thread, you need to access the UI thread via the running Dispatcher.

Access the UI thread from a different thread

You can access the current UI thread via Dispatcher.UIThread. You can either use Post or InvokeAsync, if you want to run a job on the UI thread. Use Post when you just want to start a job, but you don't need to wait for the job to be finished and you don't need the result. If you need to wait for the result, then use InvokeAsync instead.

The DispatcherPriority

The DispatcherPriority specifies at which priority the given job should be queued. For possible values please refer to the API-Reference​

Examples

In the below example we have a TextBlock which shows the result and a Button which is used to start our work.
Our view looks like this:
1
<StackPanel>
2
<TextBlock x:Name="TextBlock_Result" />
3
<Button Content="Run long running process" Click="Button_OnClick" />
4
</StackPanel>
Copied!
The long running task looks like this:
1
async Task LongRunningTask()
2
{
3
// Do some work
4
this.FindControl<TextBlock>("TextBlock_Result").Text = "I'm working ...";
5
await Task.Delay(2000);
6
this.FindControl<TextBlock>("TextBlock_Result").Text = "Done";
7
}
Copied!
Finally we can run the long running task as shown below:
1
private void Button_OnClick(object sender, RoutedEventArgs e)
2
{
3
// Start the job and return immediately
4
Dispatcher.UIThread.Post(() => LongRunningTask(), DispatcherPriority.Background);
5
}
Copied!
if we want to get the result to work with it further, we need to change the long running task to return the result:
1
async Task<string> LongRunningTask()
2
{
3
// Do some work
4
this.FindControl<TextBlock>("TextBlock_Result").Text = "I'm working ...";
5
await Task.Delay(2000);
6
this.FindControl<TextBlock>("TextBlock_Result").Text = "Done";
7
8
// return a result
9
return "Success";
10
}
Copied!
We can use the result now:
1
private async void Button_OnClick(object sender, RoutedEventArgs e)
2
{
3
// Run the job
4
var result = await Dispatcher.UIThread.InvokeAsync(LongRunningTask, DispatcherPriority.Background);
5
6
// Work with the result
7
Debug.WriteLine(result);
8
}
Copied!

Reference

​Dispatcher​

Source Code

​Dispatcher.cs​