Wednesday, February 24, 2016

Building responsive WPF UI using async, await and Task class

async void btnRun_Click(object sender, RoutedEventArgs e)
{
this.txtStatus.Text = "Running...";
this.btnRun.IsEnabled = false;

try
{
// create and queue the Task to be completed on another thread
//   and wait for it to be completed
//   while keeping the UI responsive
  // await manages retrieval of results from the completed Task
string result = await Task.Run<string>(
() =>
{
Thread.Sleep(3000);
// throw new Exception("Something went wrong");
return "Done!";
});

this.txtStatus.Text = result;
}
catch (Exception ex)
{
this.txtStatus.Text = ex.Message;
}

this.btnRun.IsEnabled = true;
}