1

我有两种与下面类似的方法。在MainThreadDoWork方法中,无论方法中的 autoResetEvent.Set() 是什么,循环都会完成执行OtherThreadWork。知道这个 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
        }
    }
4

1 回答 1

4

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

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

尝试:

AutoResetEvent autoResetEvent = new AutoResetEvent( false );
于 2012-02-21T10:37:29.473 回答