await
的天真方法通常会导致过早终止和不完整的操作。
Parallel.ForEach
解决方案:tpl dataflow
为并行的异步操作提供了强大而受控的机制。TransformBlock
>
ActionBlock
>重构代码示例
的原始代码进行并发wcf调用:TransformBlock
>
ActionBlock
<code class="language-csharp">var ids = new List<string> { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" }; var getCustomerBlock = new TransformBlock<string, Customer>( async i => { ICustomerRepo repo = new CustomerRepo(); return await repo.GetCustomer(i); }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded // Or specify a limit }); var writeCustomerBlock = new ActionBlock<Customer>(c => Console.WriteLine(c.ID)); getCustomerBlock.LinkTo(writeCustomerBlock, new DataflowLinkOptions { PropagateCompletion = true }); foreach (var id in ids) { getCustomerBlock.Post(id); } getCustomerBlock.Complete(); writeCustomerBlock.Completion.Wait();</code>
以上是我如何与并行使用Async/等待Async/等待并发呼叫?的详细内容。更多信息请关注PHP中文网其他相关文章!