async/await

Example:

private int slowFunc(int a, int b)
{
   System.Threading.Thread.Sleep(10000);
   return a + b;
}

In C# 4.0, you have to use ContinueWith():

private void btnProcessTask_Click(object sender, EventArgs e)        
{
   this.btnProcessTask.Enabled = false;          
   var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();  // get UI thread context 
   var someTask = Task<int>.Factory.StartNew(() => slowFunc(1, 2));      // create and start the Task 
   someTask.ContinueWith(x =>     
     {                                          
        this.lblTaskResults.Text = "Result: " + someTask.Result.ToString();   
        this.btnProcessTask.Enabled = true;   
     }, uiScheduler  
    );        
}

In C# 5.0, you can use async/await:

  • Add async to click event definition.
  • Add await to task needing asynchronous access. As Eric Lippert mentioned, the await operator means “if the task we are awaiting has not yet completed, then sign up the rest of this method as the continuation of that task, and then return to your caller immediately; the task will invoke the continuation when it completes.”
private async void btnProcessTask_Click(object sender, EventArgs e)
{
   this.btnProcessTask.Enabled = false; 
   var someTask = Task<int>.Factory.StartNew(() => slowFunc(1, 2)); 
   await someTask;  
   this.lblTaskResults.Text = "Result: " + someTask.Result.ToString(); 
   this.btnProcessTask.Enabled = true;
}
References