使用 async 和 await 实时更新数据

hel*_*rse 1 wpf powershell async-await

我已经尝试了这个答案中提到的代码:https : //stackoverflow.com/a/27089652/

它工作正常,我想用它在 for 循环中运行 PowerShell 脚本。GUI最初冻结然后我尝试了这个答案中提到的代码:https : //stackoverflow.com/a/35735760/

现在,当 PowerShell 脚本在后台运行时,GUI 不会冻结,尽管在 for 循环完成之前文本框中没有任何更新。我想看到实时更新的结果。这是我正在运行的代码:

        private async void run_click(object sender, RoutedEventArgs e)
        {
            Text1.Text = "";
            
            await Task.Run(() => PS_Execution(Text1));

        }

        internal async Task PS_Execution(TextBox text)
        {

            PowerShell ps = PowerShell.Create();
            ps.AddScript(script.ToString());

            {

                Collection<PSObject> results = ps.Invoke();
                foreach (PSObject r in results)
                {
                    text.Dispatcher.Invoke(() =>
                    {
                        text.Text += r.ToString();
                    });
                    await Task.Delay(100);
                }                
            }
        }
Run Code Online (Sandbox Code Playgroud)

也许我错过了一些重要的东西。请帮助我了解如何解决这个问题。

Dan*_*iel 6

而不是使用ps.Invoke()which 是同步调用,而是等待所有结果返回使用ps.BeginInvoke()。然后订阅DataAdded输出 PSDataCollection的事件并使用该操作来更新您的 ui。

private async void run_click(object sender, RoutedEventArgs e)
{
    Text1.Text = "";
    await Task.Run(() => PS_Execution(Text1));
}


internal async Task PS_Execution(TextBox text)
{
    using PowerShell ps = PowerShell.Create();
    ps.AddScript(script.ToString());

    PSDataCollection<string> input = null;
    PSDataCollection<string> output = new();
    IAsyncResult asyncResult = ps.BeginInvoke(input, output);

    output.DataAdded += (sender, args) =>
    {
        var data = sender as PSDataCollection<string>;
        text.Dispatcher.Invoke(() =>
        {
            text.Text += data[args.Index];
        });

    };
}

Run Code Online (Sandbox Code Playgroud)