2010-11-07 34 views
5

我不会提供所有代码,只是我想要做的一个示例。我有用于从外部进程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); 
    } 
}  

此代码确实出现,因为我发现一个错字到现在工作..这是正确使用?

+0

事实上,它看起来像这样做,只是我复制并粘贴它时没有将SetTextBox更改为UpdateTextBox。 – dave 2010-11-07 10:51:46

+0

您能解释一下您遇到的问题吗? – 2010-11-07 10:53:50

+0

它的工作原理,但如果我在那里放一个休息,看看在IDE中的“目标”它说“'Target.Text'抛出类型'Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException'的异常 – dave 2010-11-07 10:57:26

回答

1

您提供的代码看起来不错,并且是在线程之间发送此类消息的好方法。