下面是到目前爲止我的代碼,我有一個問題,當我打電話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;
}
它被稱爲'BeginInvoke',你期望什麼?爲什麼不使用'Invoke'? –