I’m writing a WPF application that needs to make numerous calls to a WCF services based on items in a list.
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?
If you can use C# 5.0, then
async–awaitcan help you with this. The code generator for WCF services supportsasync–await, so it can generate async versions of your methods, which will be useful.What you would do is to start all of the requests asynchronously, and store the
Tasks they return in a collection. Then, process theTasks as they complete. .Net doesn’t support that out of the box, but you can use Stephen Toub’sInterleaved()method: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.