WPF异步等待任务锁定UI线程并行运行任务

Mar*_*man 3 c# wpf multithreading asynchronous task-parallel-library

我有一个WPF应用程序,按下按钮后,创建List<Task<int>>并启动这些任务.我的假设是Add()调用并行启动这些,但异步.

这是我在远程机器上串行执行大量WMI调用的函数:

AgentBootstrapper.cs

public async Task<int> BootstrapAsync(BootstrapContext context, IProgress<BootstrapAsyncProgress> progress)
{
  ...

  do a bunch of stuff in serial *without* await calls

  ...

  if (progress != null)
  {
      progress.Report(new BootstrapAsyncProgress
      {
          MachineName = context.MachineName, 
          ProgressPercentage = 30, 
          Text = "Copying install agent software to \\\\" + context.MachineName + "\\" + context.ShareName
      });
  }

  ...

  return pid; // ProcessId of the remote agent that was just started
}
Run Code Online (Sandbox Code Playgroud)

这显然是UI中的按钮处理程序:

Shell.xaml.cs

private async void InstallButton_Click(object sender, RoutedEventArgs e)
{
    var bootstrapTasks = new List<Task<int>>();

    var progress = new Progress<BootstrapAsyncProgress>();
    progress.ProgressChanged += (o, asyncProgress) =>
    {
        Debug.WriteLine("{0}: {1}% {2}", asyncProgress.MachineName, asyncProgress.ProgressPercentage,
            asyncProgress.Text);

        //TODO Update ViewModel property for ProgressPercentage
    };

    var vm = DataContext as ShellViewModel;

    Debug.Assert(vm != null);

    foreach (var targetMachine in vm.TargetMachines)
    {
        var bootstrapContext = new BootstrapContext(targetMachine.MachineName, true)
        {
            AdminUser = vm.AdminUser,
            AdminPassword = vm.AdminPassword
        };

        var bootstrapper = new AgentBootstrapper(bootstrapContext);
        bootstrapTasks.Add(bootstrapper.BootstrapAsync(bootstrapContext, progress)); // UI thread locks up here
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道标记为async应该在其中使用函数调用的函数await.在我的例子中,这些都是对所有返回的一些同步WMi辅助函数的调用void.所以,我不认为await这就是我想要的.

简单地说,我想要所有的bootstrapTasks项目(bootstrapper.BootstrapAsync()一次性调用,并让UI线程接收来自所有项目的进度事件.当整个批次完成时,我也需要处理它.

更新1

尝试使用Task.Run()修复了UI锁定问题,但只执行了第一个Task实例.更新foreach循环:

foreach (var targetMachine in vm.TargetMachines)
{
    var tm = targetMachine; // copy closure variable
    var bootstrapContext = new BootstrapContext(tm.MachineName, true)
    {
        AdminUser = vm.AdminUser,
        AdminPassword = vm.AdminPassword
    };

    var bootstrapper = new AgentBootstrapper(bootstrapContext);

    Debug.WriteLine("Starting Bootstrap task on default thread pool...");
    var task = Task.Run(() =>
    {
        var pid = bootstrapper.Bootstrap(bootstrapContext, progress);
        return pid;
    });

    Debug.WriteLine("Adding Task<int> " + task.Id + " to List<Task<int>>.");
    tasks.Add(task);

    await Task.WhenAll(tasks);  // Don't proceed with the rest of this function untill all tasks are complete
}
Run Code Online (Sandbox Code Playgroud)

更新2

移动循环await Task.WhenAll(tasks);外部foreach允许所有任务并行运行.

Mik*_*ray 5

在生成的代码没有什么async/ await涉及线程的创建.使用该async关键字不会导致使用另一个线程.一切async都是允许您使用await关键字.如果你想在另一个线程上发生某些事情,请尝试使用Task.Run.