Turp
Turp

Reputation: 708

Multiple Web Service Calls At Once

We connect with multiple (Around 15-20) third-party web services within our C# Web Application. We are attempting to find the best way use Multi-Threading or Async to call multiple web services (2-5) at the same time.

What would be the best way to do this?

It needs the ability to:

.. All while waiting for the response for WS A, B, C, etc...

I know I need to be using IAyncResult, but i've seen some examples and some use MultiThreading and some do not. What would the best way be?

Upvotes: 2

Views: 4791

Answers (1)

Drew Marsh
Drew Marsh

Reputation: 33379

You don't mention it in your question, but you've tagged the question with the WCF tag so I'm going to assume that you are trying to make these calls with the WCF client proxy model. If this is not the case, please explain what client technology you are using and I can revise my answer.

First, I highly recommend you read this documentation on MSDN: How to: Call WCF Service Operations Asynchronously

First, what you'll be doing is generating your WCF client proxy classes with SvcUtil.exe, but specifying an additional flag, /async (or simply /a), which will generate Asynchronous Programming Model (APM) method signatures. Once you've got those client proxies generated you can simply call them like you would any other APM method and supply a callback that will be invoked once the response is available.

Utilizing the APM based WCF signatures will make the outgoing and pending network I/O completely asynchronous which will free up your "main" thread to make the 15-20 calls you need to make concurrently. Also, while the network calls are outstanding, no CPU thread will be wasted.

Now, if you're on .NET 3.5 you'll have to use some kind of synchronization primitive to wait on and signal once each of the callbacks has completed. Unfortunately there's no CountdownEvent class in 3.5 either, but you can just use Interlocked::Decrement to do the countdown and then signal a ManualResetEventSlim when it reaches 0 (or find a third party library that provides this). If you're on .NET 4.0, you can instead combine the APM model with the Task-based Asynchronous Programming (TAP) model leveraging TaskFactory::FromAsync and shove all the Tasks into a List<Task> and then use Task::WaitAll to wait for them all to complete before continuing fwd. Finally if you're on .NET 4.5 you could even combine that gracefully with C#'s async keyword and Task::WhenAll instead and save yourself a lot of manual TPL continuation logic.

Upvotes: 1

Related Questions