相关疑难解决方法(0)

使用async/await执行多个任务

我正在使用完全异步的API客户端,也就是说,每个操作都返回Task或者Task<T>,例如:

static async Task DoSomething(int siteId, int postId, IBlogClient client)
{
    await client.DeletePost(siteId, postId); // call API client
    Console.WriteLine("Deleted post {0}.", siteId);
}
Run Code Online (Sandbox Code Playgroud)

使用C#5 async/await运算符,启动多个任务并等待它们全部完成的正确/最有效方法是什么:

int[] ids = new[] { 1, 2, 3, 4, 5 };
Parallel.ForEach(ids, i => DoSomething(1, i, blogClient).Wait());
Run Code Online (Sandbox Code Playgroud)

要么:

int[] ids = new[] { 1, 2, 3, 4, 5 };
Task.WaitAll(ids.Select(i => DoSomething(1, i, blogClient)).ToArray());
Run Code Online (Sandbox Code Playgroud)

由于API客户端在内部使用HttpClient,我希望这会立即发出5个HTTP请求,并在每个请求完成时写入控制台.

.net c# task-parallel-library async-await c#-5.0

379
推荐指数
7
解决办法
23万
查看次数

在Parallel.ForEach中嵌套等待

在metro应用程序中,我需要执行许多WCF调用.有大量的调用,所以我需要在并行循环中进行调用.问题是并行循环在WCF调用完成之前退出.

你会如何重构这个按预期工作?

var ids = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
var customers = new  System.Collections.Concurrent.BlockingCollection<Customer>();

Parallel.ForEach(ids, async i =>
{
    ICustomerRepo repo = new CustomerRepo();
    var cust = await repo.GetCustomer(i);
    customers.Add(cust);
});

foreach ( var customer in customers )
{
    Console.WriteLine(customer.ID);
}

Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)

c# wcf task-parallel-library async-await parallel.foreach

159
推荐指数
9
解决办法
10万
查看次数