2013-07-18 108 views
0

下面是到目前为止我的代码,我有一个问题,当我打电话Dispatcher.BeginInvoke,它并没有在正确的时间Dispatcher.beginInvoke不立即执行

类脚本处理这些消息:

public void Execute() 
    { 
     var process = new Process(); 
     var startinfo = new ProcessStartInfo("cmd.exe", @"/C c:\test\my.bat"); 

     startinfo.WorkingDirectory = "c:\\test"; 
     startinfo.RedirectStandardOutput = true; 
     startinfo.RedirectStandardError = true; 

     startinfo.UseShellExecute = false; 
     startinfo.CreateNoWindow = true; 
     process.EnableRaisingEvents = true;  

     process.StartInfo = startinfo; 
     process.OutputDataReceived += (sender, args) => OutputDataReceived(args.Data); 
     process.ErrorDataReceived += (sender, args) => ErrorDataReceived(args.Data); 
     process.Exited += Exited; 
     process.Start(); 

     process.BeginOutputReadLine(); 
     process.BeginErrorReadLine(); 
     process.WaitForExit(); 

     int exitCode = process.ExitCode; 


     } 


    public void OutputDataReceived(string data) 
    { 
     Logging.Logger.Log("data received in script - " + data); 
     // throw event if we have a subscriber, else just return 
     if (OnScriptOutPut == null) return; 

     allFormattedOutPut += Environment.NewLine; 
     allFormattedOutPut += data; 
     allRawOutPut += data; 

     ScriptOutputEventArgs args = new ScriptOutputEventArgs(data); 
     OnScriptOutPut(this, args); 
    } 

WPF窗口调用脚本类和订阅OnScriptOutPut事件

问题是下面,updateOutPutTextBox仅被调用脚本执行完毕后,再全部updateoutputtextbox消息处理一次全部,他们没有得到亲当begininvoke被调用导致屏幕在最后得到更新而不是新的输出数据被接收时收到。任何帮助表示赞赏!

private void btnRunScript_Click(object sender, RoutedEventArgs e) 
    { 
     Script script = new Script(); 
     script.OnScriptOutPut += script_OnScriptOutPut; 

     script.Execute(); 

    } 

    private void script_OnScriptOutPut(object sender, ScriptOutputEventArgs args) 
    { 
     Application.Current.Dispatcher.BeginInvoke(new Action(() => UpdateOutPutTextBox(args.Data)),System.Windows.Threading.DispatcherPriority.Send); 

     Logging.Logger.Log("data received in event "); 
    } 

    private void UpdateOutPutTextBox(string data) 
    { 
     Logging.Logger.Log("data received in update "+data); 
     tbOutput.Text += Environment.NewLine; 
     tbOutput.Text += data; 
    } 
+0

它被称为'BeginInvoke',你期望什么?为什么不使用'Invoke'? –

回答

0

您在UI线程上调用Execute并使用WaitForExit阻止线程。然后,所有的BeginInvoke行动正在排队。取消拨打电话WaitForExit。如果您需要使用退出代码执行某些操作,请获取Exited事件处理程序中的值。

+0

谢谢!工作! –

0

我无法通过整个代码去那里, 但寻找到你的查询, Dispatcher.BeginInvoke 的BeginInvoke - >就像是异步调用,以及异步操作可能需要的时间取决于条件,使用如果可以,请调用,代码很多!尽可能减少!