1
0
mirror of https://github.com/chylex/Minecraft-Phantom-Panel.git synced 2024-11-22 08:42:44 +01:00
Minecraft-Phantom-Panel/Utils/Phantom.Utils.Runtime/WaitHandleExtensions.cs

28 lines
873 B
C#

namespace Phantom.Utils.Runtime;
public static class WaitHandleExtensions {
public static Task WaitOneAsync(this WaitHandle waitHandle, CancellationToken cancellationToken = default) {
var taskCompletionSource = new TaskCompletionSource();
void SetResult(object? state, bool timedOut) {
taskCompletionSource.TrySetResult();
}
void SetCancelled() {
taskCompletionSource.TrySetCanceled(cancellationToken);
}
var waitRegistration = ThreadPool.RegisterWaitForSingleObject(waitHandle, SetResult, null, Timeout.InfiniteTimeSpan, true);
var tokenRegistration = cancellationToken.Register(SetCancelled, useSynchronizationContext: false);
void Cleanup(Task t) {
waitRegistration.Unregister(null);
tokenRegistration.Dispose();
}
var task = taskCompletionSource.Task;
task.ContinueWith(Cleanup, CancellationToken.None);
return task;
}
}