Created
July 5, 2013 18:40
-
-
Save thomaslevesque/5936421 to your computer and use it in GitHub Desktop.
Async disposal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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