-
-
Save binki/6a5b69e28caf9cef291e09002e4755b5 to your computer and use it in GitHub Desktop.
Async disposal
This file contains hidden or 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
using System; | |
using System.Threading.Tasks; | |
class Program | |
{ | |
static void Main() => new Program().Run().Wait(); | |
async Task Run() | |
{ | |
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 | |
{ | |
try | |
{ | |
await body(resource); | |
} | |
finally | |
{ | |
await resource.DisposeAsync(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment