Skip to content

Instantly share code, notes, and snippets.

@thomaslevesque
Created July 5, 2013 18:40
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save thomaslevesque/5936421 to your computer and use it in GitHub Desktop.
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