我对遇到的跨线程访问场景感到困惑。这是我尝试做的事情:
主UI线程 - 菜单项点击时,我创建了一个后台工作线程并异步运行它。
方法
那个类中的
UI事件处理程序如下所示:
主UI线程 - 菜单项点击时,我创建了一个后台工作线程并异步运行它。
private void actionSubMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem itemSelected = (ToolStripMenuItem)sender;
ExecuteTheActionSelected(itemSelected.Text);
}
方法
ExecuteTheActionSelected
如下所示:private void ExecuteTheActionSelected(string actionSelected)
{
BackgroundWorker localBackgroundWorker = new BackgroundWorker();
localBackgroundWorker.DoWork += new DoWorkEventHandler(localBackgroundWorker_DoWork);
localBackgroundWorker.RunWorkerAsync(SynchronizationContext.Current);
}
localBackgroundWorker_DoWork
方法包含以下内容:
ActionExecutionHelper actionExecutioner = new ActionExecutionHelper()
actionExecutioner.Execute();
那个类中的
Execute
方法具有方法调用程序,实际上在UI线程中调用事件处理程序: public void Execute()
{
// ---- CODE -----
new MethodInvoker(ReadStdOut).BeginInvoke(null, null);
}
protected virtual void ReadStdOut()
{
string str;
while ((str = executionProcess.StandardOutput.ReadLine()) != null)
{
object sender = new object();
DataReceivedEventArgs e = new DataReceivedEventArgs(str);
outputDataReceived.Invoke(sender, e);
//This delegate invokes UI event handler
}
}
UI事件处理程序如下所示:
private void executionProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (_dwExecuteAction != null)
{
_dwExecuteAction.ShowDataInExecutionWindow(e.Text);
}
}
现在我们来谈谈跨线程问题:
public void ShowDataInExecutionWindow(string message)
{
if (rchtxtExecutionResults.InvokeRequired)
{
rchtxtExecutionResults.Invoke(new ShowDataExecutionDelegate(ShowDataInExecutionWindow), message);
}
else
{
this.rchtxtExecutionResults.AppendText(message + Environment.NewLine);
}
}
在这里,Invoke不会阻塞UI,而BeginInvoke会阻塞。 请帮助我理解这种情况,因为我很困惑。