Dispatcher.beginInvoke不立即执行

时间:2013-07-18 03:35:06

标签: c# wpf invoke 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;
    }

2 个答案:

答案 0 :(得分:0)

我无法完成整个代码, 但是查看你的查询, Dispatcher.BeginInvoke BeginInvoke - >就像调用异步一样,异步操作可能需要一些时间,具体取决于条件,如果可以,请使用Invoke,你的代码很多!尽可能减少它!

答案 1 :(得分:0)

您正在UI线程上调用Execute并使用WaitForExit阻止该线程。然后,所有BeginInvoke操作都排队等候。移除对WaitForExit的呼叫。如果您需要对退出代码执行某些操作,请在Exited事件处理程序中获取值。