mcamara
mcamara

Reputation: 753

Multiple concurrent webservice requests in ASP.NET using threads

I need to make multiple requests to a webservice at the same time. I thought of creating a thread for each request. Can this be done in ASP.NET v3.5?

Example:

for(int i = 0; i<=10; i++)
{
   "Do each Request in a separate thread..."
}

Upvotes: 1

Views: 4662

Answers (4)

Brian Gideon
Brian Gideon

Reputation: 48949

The following pattern can be used to spin off multiple requests as work items in the ThreadPool. It will also wait for all of those works items to complete before proceeding.

int pending = requests.Count;
var finished = new ManualResetEvent(false);
foreach (Request request in requests)
{
  Request capture = request; // Required to close over the loop variable correctly.
  ThreadPool.QueueUserWorkItem(
    (state) =>
    {
      try
      {
        ProcessRequest(capture);
      }
      finally
      {
         if (Interlocked.Decrement(ref pending) == 0) 
         {
           finished.Set();  // Signal completion of all work items.
         }
      }
    }, null);
}
finished.WaitOne(); // Wait for all work items to complete.

You could also download the Reactive Extensions backport for 3.5 and then use Parallel.For to do the same thing.

Upvotes: 2

Peter Bromberg
Peter Bromberg

Reputation: 1496

In .NET 3.5 you can use ThreadPool QueueUserWorkItem method. Plenty of examples on the web.

Upvotes: 0

Steve Wellens
Steve Wellens

Reputation: 20620

If the webservice calls are asynchronous I don't see how have multiple threads will accomplish anything.

Upvotes: 0

TehBoyan
TehBoyan

Reputation: 6890

While the oportunities to what you can use vary depending of what and where you would like to use paralelism in your code. I would suggest that you start off by using the new Task class from .NET 4.0. Example would be:

Task backgroundProcess = new Task(() =>
                {
                    service.CallMethod();
                });

This will get you started. After that I suggest that you do some reading because this is a very broad subject. Try this link:

http://www.albahari.com/threading/

Upvotes: 5

Related Questions