Await in catch and finally C# with Example



Await in catch and finally C# with Example

It is possible to use await expression to apply await operator to Tasks or Task(Of TResult) in the catch and finally 
blocks in C#6. 
It was not possible to use the await expression in the catch and finally blocks in earlier versions due to compiler 
limitations. C#6 makes awaiting async tasks a lot easier by allowing the await expression. 
try 
{ 
//since C#5 
await service.InitializeAsync(); 
} 
catch (Exception e) 
{ 
//since C#6 
await logger.LogAsync(e); 
} 
finally 
{ 
//since C#6 
await service.CloseAsync(); 
} 
It was required in C# 5 to use a bool or declare an Exception outside the try catch to perform async operations. 
 

This method is shown in the following example: 
bool error = false; 
Exception ex = null; 
try 
{ 
// Since C#5 
await service.InitializeAsync(); 
} 
catch (Exception e) 
{ 
// Declare bool or place exception inside variable 
error = true; 
ex = e; 
} 
// If you don't use the exception 
if (error) 
{ 
// Handle async task 
} 
// If want to use information from the exception 
if (ex != null) 
{ 
await logger.LogAsync(e); 
} 
// Close the service, since this isn't possible in the finally 
await service.CloseAsync(); 

0 Comment's

Comment Form

Submit Comment