建设任务从WaitHandle.Wait [英] Construct Task from WaitHandle.Wait

查看:105
本文介绍了建设任务从WaitHandle.Wait的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是选择回到任务< T> 工作从我的对象方法的图形用户界面提供方便consumation 。一些方法只需等待其他类型waithandles的互斥。有没有一种方法来构造工作 WaitHandle.Wait(),这样我就不必封闭一个treadpool线程的。

I chose to return Task<T> and Task from my objects methods to provide easy consumation by the gui. Some of the methods simply wait for mutex of other kind of waithandles . Is there a way to construct Task from WaitHandle.Wait() so that I don't have to block one treadpool thread for that.

推荐答案

有一种方法可以做到这一点:你可以使用订阅WaitHandle的<一个href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.registerwaitforsingleobject.aspx">ThreadPool.RegisterWaitForSingleObject方法,把它包通过 TaskCompletionSource 类:

There is a way to do this: you can subscribe to WaitHandle using ThreadPool.RegisterWaitForSingleObject method and wrap it via TaskCompletionSource class:

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();

这篇关于建设任务从WaitHandle.Wait的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆