有效地使用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中文網其他相關文章!