1

以下の方法と同様の方法が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
        }
    }
4

1 に答える 1

4

コンストラクターに渡されるブールパラメーターはAutoResetEvent、イベントがシグナル状態で作成されるかどうかを指定します。

すでにシグナル状態で作成しているので、最初のWaitOneブロックは発生しません。

試す:

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