我有一个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
}这显然是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
}
}我知道标记为async的函数应该在其中使用await进行函数调用。在我的例子中,这些调用都是对一些同步WMi助手函数的调用,这些函数都返回void。所以,我不认为await是我想要的。
简单地说,我想让所有的bootstrapTasks项(对bootstrapper.BootstrapAsync()的调用一次触发,并让UI线程接收来自它们的进度事件)。当整批工作完成后,我也需要处理这个问题。
更新1
尝试使用Task.Run()解决UI锁定问题,但只执行第一个任务实例。更新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
}更新2
将await Task.WhenAll(tasks);移出foreach循环允许所有任务并行运行。
发布于 2014-04-27 21:48:12
为async/await生成的代码中没有任何内容涉及线程的创建。使用async关键字不会导致使用另一个线程。async所做的就是允许您使用await关键字。如果希望在另一个线程上发生某些事情,请使用Task.Run。
发布于 2014-04-27 21:46:59
在您的UI线程中运行线程池上的任务(使用默认的任务调度程序)和它们上的await Task.WhenAll(bootstrapTasks)?
https://stackoverflow.com/questions/23329341
复制相似问题