/// <summary> /// Wait for the <see cref="AutoResetEvent"/> to enter the signaled state. /// </summary> /// <param name="waitHandle"> /// The <see cref="AutoResetEvent"/>. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> that can be used to cancel the wait operation. /// </param> /// <returns> /// <c>true</c>, if the <see cref="AutoResetEvent"/> enters the signaled state before the <see cref="CancellationToken"/> is cancelled; otherwise, <c>false</c>. /// </returns> public static bool WaitOne(this AutoResetEvent waitHandle, CancellationToken cancellationToken) { if (waitHandle == null) throw new ArgumentNullException(nameof(waitHandle)); using (AutoResetEvent timeout = new AutoResetEvent(false)) { timeout.SetIfCancelled(cancellationToken); try { WaitHandle[] bothWaitHandles = { timeout, waitHandle }; return WaitHandle.WaitAny(bothWaitHandles) == 1; } catch (TimeoutException) { return false; } } }