Cliffhangers in coding

So what am I reading? Well, come back later, I can tell you what it’s about. That sounds quite async when you have to await.
LAst year I implemented a migrationscript. After some optimizations it ran 4 hours, and the only feedback was the indication on top of the browser-tab, while the browserpage itself was empty and waiting. If I implemented this solution, it would be a nicer UX…

.Net 4.5 provides some solutions to solve this. When you have a time consuming method, you have to ‘decorate’ the method:

  • add “Async” to the methodname
  • add the async keyword to the method
  • add the await when invoking a time consuming method
public static async void DoItAsync(){
 [ codepart 1 ...]
 await TimeConsumingMethod();
 [ codepart 2...]
}

Or, when expect data in return, wrap the response in a task:

public static async Task<DataType> DoItAsync(){
 [ codepart 1 ...]
 await TimeConsumingMethod();
 [ codepart 2...]
 return datatype;
}

Remember:

  • Everything after the await keyword will be executed after the ‘TimeConsumingMethod’ is finished. Meanwhile the method ‘DoItAsync’ will return immediately.
  • Next it’s important to be aware of the call-stack. Going up you have to decorate every method ike this, until you reach the event it all started with.
async void DoIt_Click(object sender, RoutedEventArgs e)
{
 ...
 await asycnclass.DoItAsync();
 ...
}

Sauce

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s