gpt4 book ai didi

c# - 返工 EventWaitHandle 以异步等待信号

转载 作者:可可西里 更新时间:2023-11-01 09:05:13 27 4
gpt4 key购买 nike

我需要更改当前代码,以便在调用 EventWaitHandle.WaitOne 时不阻塞当前线程。问题是我正在等待系统范围的事件。我还没有找到任何合适的替代品。

代码:

EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.AutoReset, "Local event", out screenLoadedSignalMutexWasCreated);

StartOtherApp();

if (screenLoadedSignalMutexWasCreated)
{
isOtherAppFullyLoaded = handle.WaitOne(45000, true);

if (isOtherAppFullyLoaded )
{
// do stuff
}
else
{
// do stuff
}

handle.Dispose();
signalingCompleted = true;
}
else
{
isOtherAppFullyLoaded = false;
throw new Exception(" ");
}

我需要应用程序继续运行,而不是在我调用 WaitOne 的线路上停止,理想情况下会有等待。我该如何实现?

最佳答案

您可以在我的 AsyncEx library 中使用 AsyncFactory.FromWaitHandle :

isOtherAppFullyLoaded = await AsyncFactory.FromWaitHandle(handle,
TimeSpan.FromMilliseconds(45000));

实现使用ThreadPool.RegisterWaitForSingleObject:

public static Task<bool> FromWaitHandle(WaitHandle handle, TimeSpan timeout)
{
// Handle synchronous cases.
var alreadySignalled = handle.WaitOne(0);
if (alreadySignalled)
return Task.FromResult(true);
if (timeout == TimeSpan.Zero)
return Task.FromResult(false);

// Register all asynchronous cases.
var tcs = new TaskCompletionSource<bool>();
var threadPoolRegistration = ThreadPool.RegisterWaitForSingleObject(handle,
(state, timedOut) => ((TaskCompletionSource<bool>)state).TrySetResult(!timedOut),
tcs, timeout);
tcs.Task.ContinueWith(_ =>
{
threadPoolRegistration.Dispose();
}, TaskScheduler.Default);
return tcs.Task;
}

关于c# - 返工 EventWaitHandle 以异步等待信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24119429/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com