Skip to content

Instantly share code, notes, and snippets.

@noseratio
Last active May 2, 2023 11:30
Show Gist options
  • Save noseratio/133750ceebc465a93d4ecc60a0130437 to your computer and use it in GitHub Desktop.
Save noseratio/133750ceebc465a93d4ecc60a0130437 to your computer and use it in GitHub Desktop.
Handle an event with a scope
/// <summary>
/// Handle an event with a scope, e.g.:
/// </summary>
/// <example>
/// <code>
/// using (new EventHandlerScope<FormClosedEventHandler>(
/// (s, e) => cts.Cancel(),
/// handler => form.FormClosed += handler,
/// handler => form.FormClosed -= handler))
/// {
/// ...
/// }
/// </code>
/// </example>
public struct EventHandlerScope<TEventHandler> : IDisposable
where TEventHandler : Delegate
{
readonly TEventHandler _handler;
readonly Action<TEventHandler> _unsubscribe;
public EventHandlerScope(
TEventHandler handler,
Action<TEventHandler> subscribe,
Action<TEventHandler> unsubscribe)
{
_handler = handler;
_unsubscribe = unsubscribe;
subscribe(handler);
}
void IDisposable.Dispose()
{
_unsubscribe(_handler);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment