Pergunta

I've read about the task-based asynchronous pattern and it sounds great. Now, I have a WCF service that needs to call other WCF services. Those services return differnet result. How can async call those services with the new pattern and await all to complete?

Foi útil?

Solução

EDIT: If you've just got BeginXXX and EndXXX methods, see this question for how to turn those into Task<T> tasks - and then the rest of my answer will be applicable.

Basically, you need TaskFactory<T>.FromAsync(...).


You can use TaskEx.WhenAll, which will eventually be Task.WhenAll.

Note that this will wait for all the tasks to finish, even if there's an error early.

As the tasks have different result types, you'll need to set them up to start with, wait for them all to finish, then grab the results:

var t1 = service1.DoFirstTaskAsync();
var t2 = service2.DoSecondTaskAsync();
var t3 = service3.DoThirdTaskAsync();

await TaskEx.WhenAll(t1, t2, t3);

var result1 = t1.Result;
var result2 = t2.Result;
var result3 = t3.Result;

// Use the results

Alternatively, just fire off the tasks to start with, and await each one separately. Note that tasks in TAP are "hot" - they start as soon as you create them, not when you await them. So this will work too - but this time if t1 throws an exception, it won't wait for t2 and t3 to complete:

var t1 = service1.DoFirstTaskAsync();
var t2 = service2.DoSecondTaskAsync();
var t3 = service3.DoThirdTaskAsync();

var result1 = await t1;
var result2 = await t2;
var result3 = await t3;

// Use the results

I've blogged about this, first about waiting for multiple tasks in general and then about exceptions when waiting for multiple tasks.

Outras dicas

If you want to know about the plans of the WCF team to support the async/await model, take a look at the following blog post:

http://blogs.msdn.com/b/endpoint/archive/2010/11/13/simplified-asynchronous-programming-model-in-wcf-with-async-await.aspx

Amadeo

See Async CTP - How can I use async/await to call a wcf service?
for examples on async clients and services. Or use AsyncWcfLib, it supports an Actor based programming model and has examples of services calling other services inside an application or over the network.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top