简体   繁体   中英

EventWaitHandle waitOne() causes my worker thread to suspend until it has timed out

I am using a EventWaitHandle() handler. This handler is called in a ButtonClick event that waits for 10 seconds. There is another worker thread which upon receiving some data call Set() on the handler. Problem is the WaitOne() returns false after the timeout occurs. The worker thread doesnt run and looks like its suspended, hence Set() is not called. Once the timeout is over, my worker thread resumes and Set() method is called. To verify I tried without the EventWaitHandle() to check if my worker thread actually takes 10 seconds of time, but it didnt, and Set() method had hit immediately. I am not sure why the worker thread runs after the timeout has occurred in the I am new to C#. Thanks in advance

MainWindow.xaml.cs

public static EventWaitHandle autoResetEvent = new EventWaitHandle(false, EventResetMode.AutoReset);

XYZDialogBox.cs

private void BtnConnect_Click(object sender, RoutedEventArgs e)
{
MainWindow.autoResetEvent.Reset();
if (!MainWindow.autoResetEvent.WaitOne(10000))
                {
                    //Line number details is not received from Service
                    MessageBox.Show("Timeout");

                    //now disconnect and exit
                    strCommand = "#cmddisconnect " + tbIPAddress.Text + " #";
                    tcpClient.AddCommandAsync(strCommand);
                    return;
                }
}

ABC.cs

public void ABC(ref string strData)
{
   while(strData != "")
   {
     //do something
     MainWindow.autoResetEvent.Set();
   }
}

Using the async await pattern based on your code:

private async void BtnConnect_Click(object sender, RoutedEventArgs e)
{
    // await frees up the main thread but halts execution of this method until finished.
    var result  = await Task.Run(() => 
     {
          //Do something that takes time.
          // This is now in another thread.
          return MyService.ServiceCall(arg);
     });

     // use result here synchronously.
}

As an aside the example here is very rudimentary case of using the async await pattern. Ideally your service would have a library that implements an async method call that returns an awaitable task. That would look something like this.

private async void BtnConnect_Click(object sender, RoutedEventArgs e)
{
    bool success = await MyService.ServiceCallAsync(args); // async service call.

    if(success)
    {
       // handle
       return;
    }

    // an error occurred.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM