以下の方法と同様の方法が2つあります。メソッドでは、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
}
}