有效地使用TPL DataFlow
>有效处理多个异步WCF调用在处理C#中的多个异步WCF调用时,Parallel.ForEach
并不理想,因为它不直接支持await
。 一个更强大的解决方案是利用任务并行库的数据流(tpl dataflow),该数据流在管理异步操作方面擅长。
此示例演示了如何使用TPL DataFlow进行同步wcf调用的TPL DataFlow重写代码:
><code class="language-csharp">// Create a TransformBlock to asynchronously fetch Customer data. var getCustomerBlock = new TransformBlock<string, Customer>( async id => { ICustomerRepo repo = new CustomerRepo(); return await repo.GetCustomer(id); }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded // Adjust as needed }); // Create an ActionBlock to process each retrieved Customer. var writeCustomerBlock = new ActionBlock<Customer>(c => Console.WriteLine(c.ID)); // Link the blocks; PropagateCompletion ensures the pipeline finishes. getCustomerBlock.LinkTo(writeCustomerBlock, new DataflowLinkOptions { PropagateCompletion = true }); // Post IDs to the TransformBlock. foreach (var id in ids) { getCustomerBlock.Post(id); } // Signal completion and wait for all processing to finish. getCustomerBlock.Complete(); writeCustomerBlock.Completion.Wait();</code>
密钥改进:
await
tpl dataflow固有地处理TransformBlock
。
MaxDegreeOfParallelism
允许最大的并行性,但请考虑在生产环境中为更好的资源管理设定限制。
DataflowBlockOptions.Unbounded
>以上是如何在C#中同时执行多个异步WCF调用?的详细内容。更多信息请关注PHP中文网其他相关文章!