我有两种与以下方法类似的方法。在 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/