简体   繁体   English

AutoResetEvent仅在未设置时等待的最佳方式

[英]Best way for an AutoResetEvent to Wait only when not Set that number of times

I'm probably going outside of the proper design for an AutoResetEvent but don't quite know what to turn to. 我可能超出了AutoResetEvent的正确设计,但不太清楚要转向什么。 I want this behavior: 我想要这种行为:

var autoResetEvent = new AutoResetEvent(false);
autoResetEvent.Set();
autoResetEvent.Set();
autoResetEvent.WaitOne();
// since Set was called twice, I don't want to wait here
autoResetEvent.WaitOne();

Unfortunately (for my problem), this is not how an AutoResetEvent behaves. 不幸的是(对于我的问题),这不是AutoResetEvent的行为方式。 What is the best class to use for this situation? 在这种情况下,最好的课程是什么?

Note: I have access to the .NET Parallel Exensions library. 注意:我可以访问.NET Parallel Exensions库。

你在寻找信号量吗?

If you have the ability to use the Parallel Extensions Library then you should use that instead. 如果您能够使用Parallel Extensions Library,那么您应该使用它。 It is trivial to invoke worker tasks and then wait on them to finish executing. 调用工作任务然后等待它们完成执行是微不足道的。

var task = Task.Factory.StartNew(() => {
    Thread.Sleep(1000);
    Console.WriteLine("I'm Awake!");
});

Console.WriteLine("Waiting on task...");

task.Wait();

This should produce the following output: 这应该产生以下输出:

Waiting on task... 等待任务......
I'm Awake! 我很清醒!

For more reading on threading in .Net including the TPL , you should check out this exceptional resource: http://www.albahari.com/threading/ 有关.Net(包括TPL)中线程的更多阅读,您应该查看这个特殊资源: http//www.albahari.com/threading/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM