Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Async disposal
async void Main()
{
Console.WriteLine ("Before Using");
await Async.Using(new Test(), t =>
{
Console.WriteLine ("In Using body");
throw new Exception("Oops");
});
Console.WriteLine ("After Using");
}
class Test : IAsyncDisposable
{
public async Task DisposeAsync()
{
Console.WriteLine ("Disposing...");
await Task.Delay(1000);
Console.WriteLine("Disposal complete");
}
}
public interface IAsyncDisposable
{
Task DisposeAsync();
}
public static class Async
{
public static async Task Using<TResource>(TResource resource, Func<TResource, Task> body)
where TResource : IAsyncDisposable
{
Exception exception = null;
try
{
await body(resource);
}
catch(Exception ex)
{
exception = ex;
}
await resource.DisposeAsync();
if (exception != null)
{
var info = ExceptionDispatchInfo.Capture(exception);
info.Throw();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment