Below is my code so far, I am having an issue when I call Dispatcher.BeginInvoke, it does not process these messages at the correct time
Class Script:
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 calls the script class and subscribes to OnScriptOutPut event
The problem is below, UpdateOutPutTextBox only gets called after the script is finished, then all the updateoutputtextbox messages are processed all at once, they do not get processed when the begininvoke is called causing the screen to get updated at the end instead of when new output data is received.. Any help is appreciated!
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;
}
I can not go through the whole code out there, But looking into your query, Dispatcher.BeginInvoke BeginInvoke -> is like calling async , and async operations may take time depending on the conditions, use Invoke instead if you can, your code is alot ! reduse it if possible!
You are calling Execute
on the UI thread and blocking the thread with WaitForExit
. Then all of the BeginInvoke
actions are getting queued up. Remove the call to WaitForExit
. If you need to do something with the exit code, get the value in the Exited
event handler.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.