Thursday, September 5, 2013

Updating the UI thread in .NET 4.5

Recently, I had to create a WPF app for my company. In this app there were some long-running operations that had to update the UI thread when they were completed. Since I'm using MVVM and Prism, I usually start my tasks on the ViewModel and I found that using the TPL and async/await is the easiest and clearest way to synchronize my tasks:

Running=Visibility.Visible; //This is to show a hint on the view that the task is running.
var tasca=Task.Run(()=>LongRunningTask());
try{
    var result=await tasca;
    UpdateUI(result);
}
catch(Exception e){
    MessageBox.Show("Error running task");
    _log.ErrorException("Error running task",e);
}
finally{
    Running=Visibility.Collapsed;
}
This way, the code remains clear and we don't have to deal with ContinuationTasks or callbacks.