Class Defer
Invokes an action when disposed.
Implements
Inherited Members
Namespace: Recore
Assembly: Recore.dll
Syntax
public sealed class Defer : IDisposable
Remarks
Not thread-safe. Concurrent calls to dispose the object may result in the action being invoked multiple times. However, sequential calls to Dispose() are idempotent. If an instance of this type is created and never disposed, the callback will not be called. By design, the callback is not called from the finalizer, which would happen non-determinstically.
Examples
Say you want to perform some action before you exit a method, regardless of whether you return normally or throw an exception. This is usually something like releasing a resource that was acquired in the method.
The classic way to do this in C# is with try-finally
:
try
{
Console.WriteLine("Doing stuff");
}
finally
{
Console.WriteLine("Running cleanup");
}
This isn't bad, but it adds an extra level of indentation and 6 extra lines for the try-finally
.
With Defer and C# 8's new using
declarations, we can do it more simply:
using var cleanup = new Defer(() => Console.WriteLine("Running cleanup"));
Console.WriteLine("Doing stuff");
Constructors
| Improve this Doc View SourceDefer(Action)
Initializes an object with an action to invoke when the object is disposed.
Declaration
public Defer(Action action)
Parameters
Type | Name | Description |
---|---|---|
Action | action |
Methods
| Improve this Doc View SourceDispose()
Invokes the callback registered with the object and marks the object as disposed.
Declaration
public void Dispose()