代码之家  ›  专栏  ›  技术社区  ›  iamcootis

C#wpf异步向布局添加子级

  •  0
  • iamcootis  · 技术社区  · 3 年前

    我有一个WPF应用程序,其中运行一个powershell脚本,该脚本返回一系列字符串。我希望能够异步更新我的UI,但UI只会在方法完成后更新。如何异步更新UI?我已经阅读了很多类似的例子,比如: WPF User Control children not updating c# 也许这是可行的,但我可能实施得不正确?

    我的代码:

    private void NextButton_Click(object sender, RoutedEventArgs e)
            {
                RunPreCheck();
            }
    
    public void RunPreCheck()
            {
    
                var startInfo = GetPowerShellStartInfo();
                proc = Process.Start(startInfo);
    
                while (!proc.StandardOutput.EndOfStream)
                {
    
                    string line = proc.StandardOutput.ReadLine();
                    var myObject= new MyCustomObject(line);
                    myGrid.Children.Add(myObject);
              
                } 
            }
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   mm8    3 年前

    RunPreCheck()

    private void NextButton_Click(object sender, RoutedEventArgs e)
    {
        Task.Run(RunPreCheck);
    }
    
    public void RunPreCheck()
    {
        var startInfo = GetPowerShellStartInfo();
        proc = Process.Start(startInfo);
    
        while (!proc.StandardOutput.EndOfStream)
        {
            string line = proc.StandardOutput.ReadLine();
    
            myGrid.Dispatcher.BeginInvoke(
                new Action(() => myGrid.Children.Add(new MyCustomObject(line))));
    
        }
    }