From a2a4f3d82c75f35978d87767d1a746e06be57302 Mon Sep 17 00:00:00 2001 From: cinder Date: Tue, 6 May 2025 20:38:30 -0500 Subject: [PATCH] Add WaitHandleAsyncFactory --- .../Threading/WaitHandleAsyncFactory.cs | 124 ++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 LibreMetaverse/Threading/WaitHandleAsyncFactory.cs diff --git a/LibreMetaverse/Threading/WaitHandleAsyncFactory.cs b/LibreMetaverse/Threading/WaitHandleAsyncFactory.cs new file mode 100644 index 00000000..e7e40f8a --- /dev/null +++ b/LibreMetaverse/Threading/WaitHandleAsyncFactory.cs @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2014 Stephen Cleary + * Copyright (c) 2025, Sjofn LLC. + * All rights reserved. + * + * - Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * - Neither the name of the openmetaverse.co nor the names + * of its contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Threading.Tasks; +using System.Threading; + +namespace LibreMetaverse.Threading +{ + public static class WaitHandleAsyncFactory + { + /// + /// Wraps a with a . + /// When the is signalled, the returned is completed. + /// If the handle is already signalled, this method acts synchronously. + /// + /// The to observe. + public static Task FromWaitHandle(WaitHandle handle) + { + return FromWaitHandle(handle, Timeout.InfiniteTimeSpan, CancellationToken.None); + } + + /// + /// Wraps a with a . + /// If the is signalled, the returned task is completed with a true result. + /// If the observation times out, the returned task is completed with a false result. + /// If the handle is already signalled or the timeout is zero, this method acts synchronously. + /// + /// The to observe. + /// The timeout after which the is no longer observed. + public static Task FromWaitHandle(WaitHandle handle, TimeSpan timeout) + { + return FromWaitHandle(handle, timeout, CancellationToken.None); + } + + /// + /// Wraps a with a . + /// If the is signalled, the returned task is (successfully) completed. + /// If the observation is cancelled, the returned task is cancelled. + /// If the handle is already signalled or the cancellation token is already cancelled, this method acts synchronously. + /// + /// The to observe. + /// The cancellation token that cancels observing the . + public static Task FromWaitHandle(WaitHandle handle, CancellationToken token) + { + return FromWaitHandle(handle, Timeout.InfiniteTimeSpan, token); + } + + /// + /// Wraps a with a . + /// If the is signalled, the returned task is completed with a true result. + /// If the observation times out, the returned task is completed with a false result. + /// If the observation is cancelled, the returned task is cancelled. + /// If the handle has already signalled, the timeout is zero, + /// or the cancellation token has already cancelled, then this method acts synchronously. + /// + /// The to observe. + /// The timeout after which the is no longer observed. + /// The cancellation token that cancels observing the . + public static Task FromWaitHandle(WaitHandle handle, TimeSpan timeout, CancellationToken token) + { + _ = handle ?? throw new ArgumentNullException(nameof(handle)); + + // Handle synchronous cases. + var alreadySignalled = handle.WaitOne(0); + if (alreadySignalled) + return Task.FromResult(true); + if (timeout == TimeSpan.Zero) + return Task.FromResult(false); + if (token.IsCancellationRequested) + return Task.FromCanceled(new CancellationToken(true)); + + // Register all asynchronous cases. + return DoFromWaitHandle(handle, timeout, token); + } + + private static async Task DoFromWaitHandle(WaitHandle handle, TimeSpan timeout, CancellationToken token) + { + var tcs = new TaskCompletionSource(); + using (new ThreadPoolRegistration(handle, timeout, tcs)) + using (token.Register(state => ((TaskCompletionSource)state).TrySetCanceled(), + tcs, useSynchronizationContext: false)) + return await tcs.Task.ConfigureAwait(false); + } + + private sealed class ThreadPoolRegistration : IDisposable + { + private readonly RegisteredWaitHandle _registeredWaitHandle; + + public ThreadPoolRegistration(WaitHandle handle, TimeSpan timeout, TaskCompletionSource tcs) + { + _registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(handle, + (state, timedOut) => ((TaskCompletionSource)state).TrySetResult(!timedOut), tcs, + timeout, executeOnlyOnce: true); + } + + void IDisposable.Dispose() => _registeredWaitHandle.Unregister(null); + } + } +}