Using await in a catch or finally block – in C# 6.0

Using await in a catch or finally block – in C# 6.0

Using Async methods are very common now a days and while working with  async and await,  you may have experienced that you want to put some of the result awaiting either in a catch or finally block or in both. Consider a scenario, when there is an exception  and you want to log information into file or sending a service call to send exception details to server; they may take a long.   That case,  using await in an asynchronous method inside the catch block would be helpful; and this a new addition in C# 6.0

Similarly inside finally block, we can also using await to call any async method.

Following code snippet shows how this looks like.

public async Task SubmitDataToServer()
{
try
{
// Submit Data
}
catch
{
await LogExceptionAsync();
}
finally
{
await CloseConnectionAsync();
}
}

This is a very common scenarios to use await in catch and finally and would be very helpful for developer going forward.

Related Post : What’s new in C# 6.0

 

Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.

7 Comments to “Using await in a catch or finally block – in C# 6.0”

  1. Srinivasan

    I’ve a doubt in your post about “Keep tracking about Miscellaneous Files” option in solution explore of Visual Studio.
    If I enable this option in my project, whether this will be added / shown into my solution/project by default? I thought to comment this question in your post directly but there was no option to send the comment.

  2. Abhijit Jana Author

    Hi,
    You should able to see that only after adding any files. You can refer the video as well.

    P.S: Comments are automatically disabled for the posts that are older than 100 days.

Comments are closed.