等待自动重置事件 [英] Awaitable AutoResetEvent

查看:59
本文介绍了等待自动重置事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AutoResetEvent 的异步(等待)等价物是什么?

What would be the async (awaitable) equivalent of AutoResetEvent?

如果在经典的线程同步中我们会使用这样的东西:

If in the classic thread synchronization we would use something like this:

    AutoResetEvent signal = new AutoResetEvent(false);

    void Thread1Proc()
    {
        //do some stuff
        //..
        //..

        signal.WaitOne(); //wait for an outer thread to signal we are good to continue

        //do some more stuff
        //..
        //..
    }

    void Thread2Proc()
    {
        //do some stuff
        //..
        //..

        signal.Set(); //signal the other thread it's good to go

        //do some more stuff
        //..
        //..
    }

我希望在新的异步做事方式中,会变成这样:

I was hoping that in the new async way of doing things, something like this would come to be:

SomeAsyncAutoResetEvent asyncSignal = new SomeAsyncAutoResetEvent();

async void Task1Proc()
{
    //do some stuff
    //..
    //..

    await asyncSignal.WaitOne(); //wait for an outer thread to signal we are good to continue

    //do some more stuff
    //..
    //..
}

async void Task2Proc()
{
    //do some stuff
    //..
    //..

    asyncSignal.Set(); //signal the other thread it's good to go

    //do some more stuff
    //..
    //..
}

我见过其他定制的解决方案,但我设法得到的解决方案在某个时间点仍然涉及锁定线程.我不希望这只是为了使用新的 await 语法.我正在寻找一种真正的可等待信号机制,它不会锁定任何线程.

I've seen other custom made solutions, but what I've managed to get my hands on, at some point in time, still involves locking a thread. I don't want this just for the sake of using the new await syntax. I'm looking for a true awaitable signaling mechanism which does not lock any thread.

我在任务并行库中缺少什么吗?

Is it something I'm missing in the Task Parallel Library?

澄清一下:SomeAsyncAutoResetEvent 是一个完全构成的类名,在我的示例中用作占位符.

Just to make clear: SomeAsyncAutoResetEvent is an entirely made up class name used as a placeholder in my example.

推荐答案

如果您想构建自己的,Stephen Toub 有关于这个主题的权威博客文章.

If you want to build your own, Stephen Toub has the definitive blog post on the subject.

如果你想使用已经写好的一个,我的 AsyncEx 库中有一个.AFAIK,在撰写本文时没有其他选择.

If you want to use one that's already written, I have one in my AsyncEx library. AFAIK, there's no other option as of the time of this writing.

这篇关于等待自动重置事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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