Thursday 21 August 2014

Await in Catch and Finally

Leave a Comment
This is just a brief note to publicize a coming improvement to the async language support.

With the new compilers, changes to the C# language (e.g., async/await) are easier than they used to be. One improvement that is coming is the use of await in catch and finally blocks. This enables your error-handling/cleanup code to be asynchronous without awkward code mangling.

For example, let’s say that you want to (asynchronously) log an exception in one of your async methods.

The natural way to write this is:

 
try
{
  await OperationThatMayThrowAsync();
}
catch (Exception ex)
{
  await MyLogger.LogAsync(ex);
}


And this natural code works fine in Visual Studio “14”. However, the currently-released Visual Studio 2013 does not support await in a catch, so you would have to keep some kind of “error flag” and move the actual error handling logic outside the catch block:
 


Exception exception = null;
try
{
  await OperationThatMayThrowAsync();
}
catch (Exception ex)
{
  exception = ex;
}
if (exception != null)
  await MyLogger.LogAsync(exception);




This is only a simple example; in real-world code, this can get ugly rather quickly!

By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.