簡體   English   中英

Dispatcher.beginInvoke無法立即執行

[英]Dispatcher.beginInvoke not executing immediately

到目前為止,下面是我的代碼,調用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;
    }

我無法遍歷整個代碼,但是查詢查詢Dispatcher.BeginInvoke BeginInvoke->就像調用async一樣,異步操作可能需要一些時間,具體取決於條件,如果可以的話,請使用Invoke代替,您的代碼很多! 盡可能重用它!

您正在UI線程上調用Execute ,並使用WaitForExit阻止該線程。 然后,所有BeginInvoke操作都被排隊。 刪除對WaitForExit的調用。 如果您需要對退出代碼進行操作,請在Exited事件處理程序中獲取該值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM