我有两种与下面的方法相似的方法。在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
}
}发布于 2012-02-21 10:37:29
传递给AutoResetEvent构造函数的布尔参数指定事件是否以信号状态创建。
您已经将其创建为信号状态,因此您的第一个WaitOne不会阻塞。
尝试:
AutoResetEvent autoResetEvent = new AutoResetEvent( false );https://stackoverflow.com/questions/9375977
复制相似问题