c# - AutoResetEvent 在信号前触发

标签 c# .net multithreading c#-4.0 autoresetevent

我有两种与以下方法类似的方法。在 MainThreadDoWork 方法中,无论 OtherThreadWork 方法中的 autoResetEvent.Set() 是什么,循环都会完成执行。知道这个 AutoResetEvent 实例中发生了什么吗?

AutoResetEvent autoResetEvent = new AutoResetEvent(true);
private int count = 10;

private void MainThreadDoWork(object sender, EventArgs e)
{
    for (int i = 0; i < count; i++)
    {
        if (autoResetEvent.WaitOne())
        {
            Console.WriteLine(i.ToString());
        }
    }
}

private void OtherThreadWork()
{
    autoResetEvent.Set();
    //DoSomething();
}

编辑

下面是实际的 OtherThreadWork 的样子。

  private void OtherThreadWork()
    {
        if (textbox.InvokeRequired)
        {
            this.textbox.BeginInvoke(new MethodInvoker(delegate() { OtherThreadWork(); }));
            autoResetEvent.Set();
        }
        else
        {
           // Some other code
        }
    }

最佳答案

传递给 AutoResetEvent 构造函数的 bool 参数指定事件是否在信号状态下创建。

您创建的它已经处于信号状态,因此您的第一个 WaitOne 不会阻塞。

尝试:

AutoResetEvent autoResetEvent = new AutoResetEvent( false );

关于c# - AutoResetEvent 在信号前触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9375977/

相关文章:

c# - 任务并行库WaitAll异常处理

java - 在某些条件下在同步和异步模式之间切换

c - 在线程中使用不同的互斥锁

c# - 为什么 Enumerable.Cast 引发 InvalidCastException?

.net - 寻找基于C#或.Net的验收测试框架-Aqua或Robot的替代产品

c# Reporting Services -- ReportParameter 值不是字符串

.net - 使用反射获取嵌套属性值

ios - 如何在 ios 中使用 GCD 获取队列中的数据

c# - .net 中的 mongodb orm/odm?

c# - 温莎城堡 : Register by Convention with Named part