C# async ctp is an exceptional ctp, i normally avoid preview, ctp, beta stuff
but this one is different

So you know how async works

//===========================
await FetchFromDatabaseAsync();
 ShowDatabaseDataOnDataGrid();
 //===========================

ShowDatabaseDataOnDataGrid —> this will wait to execute until FetchFromDatabaseAsync is complete

sometimes, you want to preload / prefetch some data
you want to have a button to ShowDatabaseDataOnDataGrid();

//This will wait until FetchFromDatabase is complete, then your button is clickable
 //=========================
 await FetchFromDatabaseAsync();
 button.Click+=(s,e)=>
 {
 ShowDatabaseDataOnDataGrid();
 };
 //=========================

//this one error due your data is not ready
 //=======================
 button.Click+=(s,e)=> {    ShowDatabaseDataOnDataGrid(); };
 FetchFromDatabaseAsync();
 //=======================

a thing to remember is c# async is task based approach
use GetAwaiter

GetAwaiter basically a variable which hold a continueation of your task

//===================
 var w=FetchFromDatabaseAsync().GetAwaiter();
 button.Click+=(s,e)=>
 {
 w.OnComplete(()=>
 {
 ShowDatabaseDataOnDataGrid();
 });
 };
 //====================

this way, your button is responsive and wait for sure that the data is loaded

See @Stephen Toub for more complete explanation

http://blogs.msdn.com/b/pfxteam/archive/2011/01/13/10115642.aspx

Advertisements