在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) 我对我认为纯粹是异步程序的输出感到困惑。如您所见,没有明显的反模式(希望如此)和阻止呼叫。
slowURL限制服务器响应10秒钟。我确实通过在10秒钟的超时时间内运行对本地服务器的调用来确认,FetchSlowAsync在控制台中运行代码时,该方法调用有效地阻塞了主线程10秒钟。
我希望TaskScheduler不会按顺序安排调用,而是总是随机确定方法的调用顺序。las,输出始终是确定性的。
FetchSlowAsync start
FetchSlowAsync got data!
FetchAsync start
FetchAsync got data!
FetchBingAsync start
FetchBingAsync got data!
All done!
Run Code Online (Sandbox Code Playgroud)
我的问题是:是什么促使FetchSlowAsync阻塞而不是TaskScheduler执行上下文切换到另一个异步方法,并在完成后返回到它?
下一个问题是前一个问题:async Main在异步执行模型是并发的情况下,为什么其中的所有方法都按照被调用的相同顺序执行?
FetchSlowAsync start
FetchSlowAsync got data!
FetchAsync start
FetchAsync got data!
FetchBingAsync start
FetchBingAsync got data!
All done!
Run Code Online (Sandbox Code Playgroud) c# ×3
async-await ×2
.net-core ×1
asynchronous ×1
c#-5.0 ×1
concurrency ×1
multicore ×1
wcf ×1