Created
April 29, 2022 20:55
-
-
Save Warrenn/d3ab090a265703ab902f7715a6e28ccb to your computer and use it in GitHub Desktop.
await events using Task
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
namespace Auto_Invest; | |
public static class EventAwaiter | |
{ | |
public class EventArg<T> | |
{ | |
public T? Args { get; set; } | |
public object? Sender { get; set; } | |
} | |
public static Task<EventArg<T>> AwaitEvent<T>(Action<EventHandler<T>> addEvent, Action<EventHandler<T>> removeEvent, Action? initiate = null) | |
{ | |
var source = new TaskCompletionSource<EventArg<T>>(); | |
addEvent(Handler); | |
initiate?.Invoke(); | |
return source.Task; | |
void Handler(object? sender, T e) | |
{ | |
removeEvent(Handler); | |
source.SetResult(new EventArg<T> { Args = e, Sender = sender }); | |
} | |
} | |
public static Task<EventArg<EventArgs>> AwaitEvent(Action<EventHandler> addEvent, Action<EventHandler> removeEvent, Action? initiate = null) | |
{ | |
var source = new TaskCompletionSource<EventArg<EventArgs>>(); | |
addEvent(Handler); | |
initiate?.Invoke(); | |
return source.Task; | |
void Handler(object? sender, EventArgs e) | |
{ | |
removeEvent(Handler); | |
source.SetResult(new EventArg<EventArgs> { Args = e, Sender = sender }); | |
} | |
} | |
public static Task<T> AwaitEvent<T>(Action<Action<T>> addEvent, Action<Action<T>> removeEvent, Action? initiate = null) | |
{ | |
var source = new TaskCompletionSource<T>(); | |
addEvent(Handler); | |
initiate?.Invoke(); | |
return source.Task; | |
void Handler(T e) | |
{ | |
removeEvent(Handler); | |
source.SetResult(e); | |
} | |
} | |
public static Task AwaitEvent(Action<Action> addEvent, Action<Action> removeEvent, Action? initiate = null) | |
{ | |
var source = new TaskCompletionSource(); | |
addEvent(Handler); | |
initiate?.Invoke(); | |
return source.Task; | |
void Handler() | |
{ | |
removeEvent(Handler); | |
source.SetResult(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment