使用異步/等待和TPL DataFlow處理並發WCF調用
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中文網其他相關文章!