It sometimes want to block my thread while waiting for a event to occur.
I usually do it something like this:
private AutoResetEvent _autoResetEvent
You may also try this:
class EventWaiter where TEventArgs : EventArgs
{
private readonly Action> _unsubHandler;
private readonly Action> _subHandler;
public EventWaiter(Action> subHandler, Action> unsubHandler)
{
_unsubHandler = unsubHandler;
_subHandler = subHandler;
}
protected void Handler(object sender, TEventArgs args)
{
_unsubHandler.Invoke(Handler);
TaskCompletionSource.SetResult(args);
}
public TEventArgs WaitOnce()
{
TaskCompletionSource = new TaskCompletionSource();
_subHandler.Invoke(Handler);
return TaskCompletionSource.Task.Result;
}
protected TaskCompletionSource TaskCompletionSource { get; set; }
}
Usage:
EventArgs eventArgs = new EventWaiter((h) => { button.Click += new EventHandler(h); }, (h) => { button.Click -= new EventHandler(h); }).WaitOnce();