Last active
May 2, 2023 11:30
-
-
Save noseratio/133750ceebc465a93d4ecc60a0130437 to your computer and use it in GitHub Desktop.
Handle an event with a scope
This file contains 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
/// <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