如何制作非阻塞等待句柄

本文关键字:等待 句柄 何制作 | 更新日期: 2023-09-27 18:28:45

本质上,我要做的是创建一个web服务器来处理API调用,然后在完成后继续执行方法,所以本质上:

new WebServer(myAutoResetEvent);
myAutoResetEvent.WaitOne();

但是,在那之前,这会阻塞线程。有什么方法可以使这个异步吗?仅将其封装在await Task.Run()调用(即await Task.Run(() => myAutoResetEvent.WaitOne()))中可以吗?

谢谢!

如何制作非阻塞等待句柄

通常,WebServer ctor不应该做任何有趣的事情。应该有一个Task WebServer.RunAsync函数来运行服务器。然后,您可以使用生成的任务进行同步和协调。

如果您不希望这样,可以使用TaskCompletionSource<object>作为一次性异步就绪事件。

我相信ThreadPool类有一种方法可以有效地等待WaitHandle的设置,但这是一个更糟糕的解决方案。

您不应该阻塞ThreadPool线程,这是导致ThreadPool饥饿的一种快速方法,相反,提供了一种异步等待WaitHandle实例的方法,称为ThreadPool.RegisterWaitForSingleObject

通过使用ThreadPool.RegisterWaitForSingleObject,当WaitHandle可用时,会注册回调以调用,不幸的是,这不是开箱即用的异步/等待兼容,使这种异步/等待兼容性的完整实现如下:

public static class WaitHandleExtensions
{
    public static Task WaitOneAsync(this WaitHandle waitHandle, CancellationToken cancellationToken)
    {    
        return WaitOneAsync(waitHandle, Timeout.Infinite, cancellationToken);
    }
    public static async Task<bool> WaitOneAsync(this WaitHandle waitHandle, int timeout, CancellationToken cancellationToken)
    {    
        // A Mutex can't use RegisterWaitForSingleObject as a Mutex requires the wait and release to be on the same thread
        // but RegisterWaitForSingleObject acquires the Mutex on a ThreadPool thread.
        if (waitHandle is Mutex)
            throw new ArgumentException(StringResources.MutexMayNotBeUsedWithWaitOneAsyncAsThreadIdentityIsEnforced, nameof(waitHandle));
        cancellationToken.ThrowIfCancellationRequested();
        var tcs = new TaskCompletionSource<bool>();
        var rwh = ThreadPool.RegisterWaitForSingleObject(waitHandle, OnWaitOrTimerCallback, tcs, timeout, true);
        var cancellationCallback = BuildCancellationCallback(rwh, tcs);
        using (cancellationToken.Register(cancellationCallback))
        {
            try
            {
                return await tcs.Task.ConfigureAwait(false);
            }
            finally
            {
                rwh.Unregister(null);
            }
        }
    }
    private static Action BuildCancellationCallback(RegisteredWaitHandle rwh, TaskCompletionSource<bool> tcs)
    {    
        return () =>
        {
            if (rwh.Unregister(null))
            {
                tcs.SetCanceled();
            }
        };
    }
    private static void OnWaitOrTimerCallback(object state, bool timedOut)
    {    
        var taskCompletionSource = (TaskCompletionSource<bool>)state;
        taskCompletionSource.SetResult(!timedOut);
    }
}

唯一的限制是它不能与Mutex一起使用。

这可以这样使用:

await myAutoResetEvent.WaitOneAsync(cancellationToken).ConfigureAwait(false);

另一种需要考虑的方法是使用HttpSelfHostServer(System.Web.Http.SelfHost.dll),并将所有线程细节留给其实现。

var config = new HttpSelfHostConfiguration("http://localhost:9999");
var tcs = new TaskCompletionSource<Uri>();
using (var server = new HttpSelfHostServer(config, new MessageHandler(tcs)))
{
    await server.OpenAsync();
    await tcs.Task;
    await server.CloseAsync();
}
return tcs.Task.Result;
class MessageHandler : HttpMessageHandler
{
    private readonly TaskCompletionSource<Uri> _task;
    public MessageHandler(TaskCompletionSource<Uri> task)
    {
        _task = task;
    }
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        _task.SetResult(request.RequestUri);
        return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
    }
}