到目前为止,以下是我的代码,当我调用 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 Window 调用脚本类并订阅 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;
}