Skip to content

Instantly share code, notes, and snippets.

@kaorun55
Created March 14, 2012 09:25
Show Gist options
  • Save kaorun55/2035344 to your computer and use it in GitHub Desktop.
Save kaorun55/2035344 to your computer and use it in GitHub Desktop.
async/await
private void Button_Click_1( object sender, RoutedEventArgs e )
{
//HeavyProcess();
var stopwatch = Stopwatch.StartNew();
var stopwatch2 = Stopwatch.StartNew();
this.button1.IsEnabled = false; //prevent re-entry
var someTask = Task<Task<int>>.Factory.StartNew( () => slowFunc( 1, 2 ) );
someTask.ContinueWith( x =>
{
this.label1.Text = "Result: " + someTask.Result.Result.ToString();
this.button1.IsEnabled = true;
stopwatch2.Stop();
},
TaskScheduler.FromCurrentSynchronizationContext() );
//this.label1.Text = "Result: " + someTask.Result.Result.ToString(); //oops, blocks calling thread
//this.button1.IsEnabled = true;
stopwatch.Stop();
new MessageDialog( string.Format( "{0}ms, {1}ms", stopwatch.ElapsedMilliseconds, stopwatch2.ElapsedMilliseconds ) ).ShowAsync();
}
private async Task<int> slowFunc( int a, int b )
{
await Task.Delay( TimeSpan.FromSeconds( 5 ) );
return a + b;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment