简体   繁体   English

使用任务循环异步WCF调用

[英]Async WCF calls in a loop using tasks

I'm writing a WPF application that needs to make numerous calls to a WCF services based on items in a list. 我正在编写一个WPF应用程序,该应用程序需要基于列表中的项目对WCF服务进行大量调用。

foreach(var item in items)
{
    var dataAboutItem = MethodThatCallsWCFService(item);

    //  Do work to update UI
    .
    .
    .
}

Is there a smart way to do this using Tasks/Parallel.ForEach or some construct in the TPL that will let me make all the service calls on background threads and then update the UI accordingly as results come in for each call? 是否有一种聪明的方法可以使用Tasks / Parallel.ForEach或TPL中的某些构造来执行此操作,从而让我在后台线程上进行所有服务调用,然后根据每次调用的结果来相应地更新UI?

If you can use C# 5.0, then async - await can help you with this. 如果可以使用C#5.0,则async - await可以帮助您。 The code generator for WCF services supports async - await , so it can generate async versions of your methods, which will be useful. WCF服务的代码生成器支持async - await ,因此它可以生成方法的异步版本,这将很有用。

What you would do is to start all of the requests asynchronously, and store the Task s they return in a collection. 您要做的是异步启动所有请求,并将它们返回的Task存储在集合中。 Then, process the Task s as they complete. 然后,在完成Task处理。 .Net doesn't support that out of the box, but you can use Stephen Toub's Interleaved() method : .Net不支持开箱即用,但是您可以使用Stephen Toub的Interleaved()方法

var tasks = new List<Task<DataAboutItem>>();

foreach (var item in items)
{
    // don't await here yet
    Task<DataAboutItem> dataAboutItemTask = MethodThatCallsWCFServiceAsync(item);

    tasks.Add(dataAboutItemTask);
}

foreach (var bucket in Interleaved(tasks))
{
    var dataAboutItemTask = await bucket;
    DataAboutItem dataAboutItem = await dataAboutItemTask;

    //  Do work to update UI
}

If you wanted to throttle calling the WCF service (for example, only make 10 requests at a time), you could instead use TPL Dataflow, specifying MaxDegreeOfParallelism . 如果要限制调用WCF服务(例如,一次仅发出10个请求),则可以改用TPL Dataflow,指定MaxDegreeOfParallelism

Task Parallel Library 任务并行库

Parallel.ForEach 并行并行

Last sample has UI 最后一个样本具有用户界面

Potential Pitfalls in Data and Task Parallelism 数据和任务并行性的潜在陷阱

Or update a public property the UI is bound to rather than the UI directly. 或更新UI绑定到的公共属性,而不是直接更新UI。

If this is not going to load CPU you may want to use MaxDegreeOfParallelism to keep too many thread from spinning up. 如果这不会加载CPU,则可能需要使用MaxDegreeOfParallelism来防止过多的线程旋转。

ParallelOptions.MaxDegreeOfParallelism ParallelOptions.MaxDegreeOfParallelism

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM