Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct Task from WaitHandle.Wait

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.

like image 218
user629926 Avatar asked Dec 06 '12 10:12

user629926


1 Answers

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;
    }
}

Usage:

WaitHandle wh = new AutoResetEvent(true);
var task = wh.ToTask();
task.Wait();
like image 72
Sergey Teplyakov Avatar answered Nov 10 '22 00:11

Sergey Teplyakov