返工EventWaitHandle以异步等待信号

时间:2014-06-09 11:33:13

标签: c# multithreading asynchronous

当调用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的行上,理想情况下会有等待。我该如何实现呢?

1 个答案:

答案 0 :(得分:13)

您可以在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;
}