【发布时间】:2012-05-08 11:26:30
【问题描述】:
我对跨线程访问遇到的场景感到困惑。这是我想要做的:
主 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 不会像 BeginInvoke 那样阻止 UI。 请帮助我理解这种情况,因为我很困惑。
【问题讨论】:
-
恐怕我不知道答案,但我要找出答案的方法是查看多个级别的调用和后台工作人员如何相互作用,以及在哪里一切都实际执行,以便您了解一切如何组合在一起。
标签: c# winforms multithreading begininvoke invokerequired