【问题标题】:Using async and await that updates data in real time使用异步和等待实时更新数据
【发布时间】:2021-10-06 23:57:37
【问题描述】:

我已经尝试过这个答案中提到的代码: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);
                }                
            }
        }

也许我错过了一些重要的事情。请帮助我了解如何解决此问题。

【问题讨论】:

  • 这能回答你的问题吗? Write PowerShell Output (as it happens) to WPF UI Control 或简单地使用Start-Job,如here
  • 您缺少的最重要的事情是您对 UI 元素接收数据的主要方式的无知:绑定到数据上下文属性。如果已为 text.Text 分配绑定,则不需要 Dispatcher 调用。更改 Bind 源属性的值就足够了。

标签: wpf powershell async-await


【解决方案1】:

不要使用ps.Invoke(),它是同步调用,将等待所有结果返回,而是使用ps.BeginInvoke()。然后订阅输出 PSDataCollection 的DataAdded 事件并使用该操作更新您的 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];
        });

    };
}

【讨论】:

    猜你喜欢
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    相关资源
    最近更新 更多