[英]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.