簡體   English   中英

EventWaitHandle waitOne() 導致我的工作線程掛起直到超時

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

我正在使用 EventWaitHandle() 處理程序。 此處理程序在等待 10 秒的 ButtonClick 事件中調用。 還有另一個工作線程在處理程序上接收到一些數據調用 Set() 時。 問題是 WaitOne() 在超時發生后返回 false。 工作線程沒有運行並且看起來像是掛起的,因此沒有調用 Set()。 超時結束后,我的工作線程將恢復並調用 Set() 方法。 為了驗證,我嘗試在沒有 EventWaitHandle() 的情況下檢查我的工作線程是否實際需要 10 秒的時間,但它沒有,並且 Set() 方法立即命中。 我不知道為什么工作線程在我是 C# 新手中發生超時后運行。 提前致謝

主窗口.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();
   }
}

根據您的代碼使用異步等待模式:

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.
}

順便說一句,這里的示例是使用異步等待模式的非常基本的情況。 理想情況下,您的服務應該有一個實現異步方法調用的庫,該調用返回一個可等待的任務。 那看起來像這樣。

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.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM