Skip to content

Instantly share code, notes, and snippets.

@MZachmann
Last active October 6, 2018 23:23
Show Gist options
  • Save MZachmann/c55648ca4d13f4c090e624a1938d6567 to your computer and use it in GitHub Desktop.
Save MZachmann/c55648ca4d13f4c090e624a1938d6567 to your computer and use it in GitHub Desktop.
A Method that waits for an Event to trigger or a timeout.
using System.Threading;
using System.Windows.Threading;
/// <summary>
/// Wait for an Event to trigger or for a timeout
/// </summary>
/// <param name="eventHandle">The event to wait for</param>
/// <param name="timeout">Maximum time to wait</param>
/// <returns>true if the event triggered, false on timeout</returns>
private bool WaitForEvent(EventWaitHandle eventHandle, TimeSpan timeout)
{
bool didWait = false;
var frame = new DispatcherFrame();
new Thread(() =>
{
// asynchronously wait for the event/timeout
didWait = eventHandle.WaitOne(timeout);
// signal the secondary dispatcher to stop
frame.Continue = false;
}).Start();
Dispatcher.PushFrame(frame); // start the secondary dispatcher, pausing this code
return didWait;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment