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

遍及 Whosebug,但我无法使其正常工作或找到答案。或者答案不适用于我正在做的事情,或者答案中没有足够的信息让我理解如何进行这项工作。

我试图在这里编写好的代码并避免 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。