Last active
October 16, 2021 16:09
-
-
Save uladz-zubrycki/901b6194167834658235dad6c84f81a0 to your computer and use it in GitHub Desktop.
Disposable delegate
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
| public static class Disposable | |
| { | |
| public static IDisposable Create(Action dispose) => | |
| new DisposableAction(dispose); | |
| public static IAsyncDisposable Create(Func<ValueTask> dispose) => | |
| new AsyncDisposableAction(dispose); | |
| private sealed class DisposableAction: IDisposable | |
| { | |
| private readonly Action dispose; | |
| private bool isDisposed; | |
| public DisposableAction(Action dispose) | |
| { | |
| this.dispose = dispose ?? throw new ArgumentNullException(nameof(dispose)); | |
| } | |
| public void Dispose() | |
| { | |
| if (isDisposed) | |
| { | |
| return; | |
| } | |
| isDisposed = true; | |
| this.dispose(); | |
| } | |
| } | |
| private sealed class AsyncDisposableAction: IAsyncDisposable | |
| { | |
| private readonly Func<ValueTask> dispose; | |
| private bool isDisposed; | |
| public AsyncDisposableAction(Func<ValueTask> dispose) | |
| { | |
| this.dispose = dispose ?? throw new ArgumentNullException(nameof(dispose)); | |
| } | |
| public ValueTask DisposeAsync() | |
| { | |
| if (isDisposed) | |
| { | |
| return default; | |
| } | |
| isDisposed = true; | |
| return this.dispose(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment