Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@binki
Forked from thomaslevesque/AsyncDisposal.cs
Last active April 10, 2019 20:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save binki/6a5b69e28caf9cef291e09002e4755b5 to your computer and use it in GitHub Desktop.
Save binki/6a5b69e28caf9cef291e09002e4755b5 to your computer and use it in GitHub Desktop.
Async disposal
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