【发布时间】:2010-11-07 10:47:00
【问题描述】:
我不会提供所有代码,而是我想要做的一个示例。我有这段代码用于从外部进程 stderr 更新 GUI 元素。
我这样设置我的流程:
ProcessStartInfo info = new ProcessStartInfo(command, arguments);
// Redirect the standard output of the process.
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
info.CreateNoWindow = true;
// Set UseShellExecute to false for redirection
info.UseShellExecute = false;
proc = new Process();
proc.StartInfo = info;
proc.EnableRaisingEvents = true;
// Set our event handler to asynchronously read the sort output.
proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
proc.ErrorDataReceived += new DataReceivedEventHandler(proc_ErrorDataReceived);
proc.Exited += new EventHandler(proc_Exited);
proc.Start();
// Start the asynchronous read of the sort output stream. Note this line!
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
然后我有一个事件处理程序
void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
UpdateTextBox(e.Data);
}
}
它调用以下,它引用一个特定的文本框控件。
private void UpdateTextBox(string Text)
{
if (this.InvokeRequired)
this.Invoke(new Action<string>(this.SetTextBox), Text);
else
{
textBox1.AppendText(Text);
textBox1.AppendText(Environment.NewLine);
}
}
我想要的是这样的:
private void UpdateTextBox(string Text, TextBox Target)
{
if (this.InvokeRequired)
this.Invoke(new Action<string, TextBox>(this.SetTextBox), Text, Target);
else
{
Target.AppendText(Text);
Target.AppendText(Environment.NewLine);
}
}
我可以使用该线程更新不同的文本框,而无需为 GUI 中的每个控件创建单独的函数。
这可能吗? (显然上面的代码不能正常工作)
谢谢。
更新:
private void UpdateTextBox(string Text, TextBox Target)
{
if (this.InvokeRequired)
this.Invoke(new Action<string, TextBox>(this.**UpdateTextBox**), Text, Target);
else
{
Target.AppendText(Text);
Target.AppendText(Environment.NewLine);
}
}
这个代码现在似乎可以工作了,因为我注意到一个错字.. 可以使用吗?
【问题讨论】:
-
其实它看起来确实有效,只是我在复制和粘贴时没有将 SetTextBox 更改为 UpdateTextBox。
-
您能解释一下您遇到的问题吗?
-
它可以工作,但如果我在那里休息并查看 IDE 中的“Target”,它会说“'Target.Text' 引发了类型为 'Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException '"
标签: c# .net winforms multithreading