我不會提供所有代碼,只是我想要做的一個示例。我有用於從外部進程stderr更新GUI元素的代碼。如何在運行System.Diagnostics進程時在線程之間傳遞對象
設置我的過程是這樣的:
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控制創建一個單獨的功能。
這可能嗎? (顯然上面的代碼無法正常工作)
謝謝。
UPDATE:
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。 – dave 2010-11-07 10:51:46
您能解釋一下您遇到的問題嗎? – 2010-11-07 10:53:50
它的工作原理,但如果我在那裏放一個休息,看看在IDE中的「目標」它說「'Target.Text'拋出類型'Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException'的異常 – dave 2010-11-07 10:57:26