Search code examples
c#.netmultithreadingc#-4.0autoresetevent

AutoResetEvent fire before signal


I've two similar methods to below ones. In the MainThreadDoWork method the loop is finish executing regardless of the autoResetEvent.Set() in the OtherThreadWork method. Any idea what's happening in this AutoResetEvent instance?

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();
}

EDIT

Below is how actual OtherThreadWork looks like.

  private void OtherThreadWork()
    {
        if (textbox.InvokeRequired)
        {
            this.textbox.BeginInvoke(new MethodInvoker(delegate() { OtherThreadWork(); }));
            autoResetEvent.Set();
        }
        else
        {
           // Some other code
        }
    }

Solution

  • The boolean parameter passed to the AutoResetEvent constructor specifies if the event is created in the signalled state or not.

    You're creating it already in the signalled state, so your first WaitOne won't block.

    Try:

    AutoResetEvent autoResetEvent = new AutoResetEvent( false );