Working with Tasks is pretty easy. You can do very easy things that would be pretty complicated to do using threads. In today post I want to talk a little bit about UI threads and tasks.
If you are working on a Windows Store App, Windows Phone or WPF application then you will have the following case:
From a task I want to be able to update a UI component (a label for example).
By default this is not possible, if you are trying to run the task from the UI thread then you don’t resolve the problem. The task will still run on the UI thread and if you have a long task then you will block the UI.
The solution is to run only the lines of code that update the UI components on a task that runs on UI. If the code that updates the UI is at the end of the task then you can have something like this:
If you are working on a Windows Store App, Windows Phone or WPF application then you will have the following case:
From a task I want to be able to update a UI component (a label for example).
By default this is not possible, if you are trying to run the task from the UI thread then you don’t resolve the problem. The task will still run on the UI thread and if you have a long task then you will block the UI.
The solution is to run only the lines of code that update the UI components on a task that runs on UI. If the code that updates the UI is at the end of the task then you can have something like this:
var blueTask = Task<string>.Run(() =>
{
...
return value;
})
.ContinueWith(value =>
{
...
this.MyLabel.Text = value;
}, TaskScheduler.FromCurrentSynchronizationContext());
If the code has to display a dialog box and you need a response then you can create a task inside your task that runs on the UI task:var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext;
var blueTask = Task<string>.Run(() =>
{
...
await Task.Factory.StartNew(
() => this.MyLabel.Text = value,
CancellationToken.None, TaskCreationOptions.None, uiScheduler);
return value;
});
Enjoy!
Comments
Post a Comment