我选择从我的对象中返回Task<T>
和返回Task
方法,以便通过 gui 轻松使用。一些方法只是等待其他类型的等待句柄的互斥体。有没有一种方法可以构建Task
,WaitHandle.Wait()
这样我就不必为此阻塞一个treadpool线程。
问问题
4810 次
2 回答
18
有一种方法可以做到这一点:您可以使用ThreadPool.RegisterWaitForSingleObject方法订阅 WaitHandle 并通过TaskCompletionSource类对其进行包装:
public static class WaitHandleEx
{
public static Task ToTask(this WaitHandle waitHandle)
{
var tcs = new TaskCompletionSource<object>();
// Registering callback to wait till WaitHandle changes its state
ThreadPool.RegisterWaitForSingleObject(
waitObject: waitHandle,
callBack:(o, timeout) => { tcs.SetResult(null); },
state: null,
timeout: TimeSpan.MaxValue,
executeOnlyOnce: true);
return tcs.Task;
}
}
用法:
WaitHandle wh = new AutoResetEvent(true);
var task = wh.ToTask();
task.Wait();
于 2012-12-06T11:13:35.903 回答
11
正如@gordy 在 Sergey Teplyakov 接受的答案的评论中所指出的那样,MSDN提出了一个取消订阅已注册 WaitHandle 的实现。
我这里稍微修改了一下,支持回调的结果:如果注册超时,任务返回false。如果已收到信号,则任务返回 true:
public static class ExtensionMethods
{
public static Task<bool> WaitOneAsync(this WaitHandle waitHandle, int timeoutMs)
{
if (waitHandle == null)
throw new ArgumentNullException(nameof(waitHandle));
var tcs = new TaskCompletionSource<bool>();
RegisteredWaitHandle registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(
waitHandle,
callBack: (state, timedOut) => { tcs.TrySetResult(!timedOut); },
state: null,
millisecondsTimeOutInterval: timeoutMs,
executeOnlyOnce: true);
return tcs.Task.ContinueWith((antecedent) =>
{
registeredWaitHandle.Unregister(waitObject: null);
try
{
return antecedent.Result;
}
catch
{
return false;
}
});
}
}
用法与原始答案相同:
WaitHandle signal = new AutoResetEvent(initialState: false);
bool signaled = await signal.WaitOneAsync(1000);
if (signaled)
{
Console.WriteLine("Signal received");
}
else
{
Console.WriteLine("Waiting signal timed out");
}
于 2018-03-22T12:34:55.573 回答