簡體   English   中英

C#從后台線程正確引發事件並在UI線程中處理它

[英]C# Properly raise event from background thread and handle it in the UI thread

我一直在網上尋找這樣的例子:

https://msdn.microsoft.com/en-us/library/edzehd2t%28v=vs.110%29.aspx

和整個stackoverflow,但我無法讓它工作或找到答案。 或者答案不適用於我正在做的事情,或者答案中沒有足夠的信息讓我了解如何進行這項工作。

我試圖在這里編寫好的代碼並避免 Application.DoEvents()。 看一下代碼。

private void btnSendQ_Click(object sender, EventArgs e)
{
     //launch a thread from a button click event
     Thread ManualQueryThread = new Thread(StartManualQueryThread_Thread);
     ManualQueryThread.Priority = ThreadPriority.Normal;
     ManualQueryThread.IsBackground = true;
     Platform.Log(LogLevel.Debug, "Starting Manual Query Thread.");
     Stats.g_CurrentStatus = "Starting Manual Query Thread.";
     ManualQueryThread.Start();

}

private void StartManualQueryThread_Thread()
{
     try
     {
        //Here work is performed in the background thread populating objects with data.
     }
     catch (Exception e)
     {
          Platform.Log(LogLevel.Error, "Error in StartManualQueryThread(). The error is: " + e.ToString());
     }
     finally
     {
          //raise event here since the thread has completed
          OnC_FindComplete(EventArgs.Empty);                    
     }
}

    public event EventHandler C_FindComplete;

    protected virtual void OnC_FindComplete(EventArgs e)
    {
        //display the gathered information in a datagrid using DisplayC_FindResults(), and enable UI objects.
        EventHandler handler = C_FindComplete;        
        DisplayC_FindResults();
        btnSendQ.Enabled = true;
        btnMove.Enabled = true;
    }

問題是當創建發布版本時,數據網格會收到空引用異常並執行紅色 X 操作,因為它仍在由后台線程更新。 那么如何在后台線程中正確引發事件,並在 UI 線程中處理該事件以與 UI 交互呢?

嘗試使用BackgroundWorker 您將能夠在RunWorkerCompleted事件中更新您的 UI。

暫無
暫無

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

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