0

I have the following problem: I am making several requests in a webservice via HttpWebRequest, as follows. I'm creating a list of all requests, then I do one on my list is calling each request. It turns out that to run everything, my page is waiting for all requests and then the page is released. What I like to do? For each request, the system would make a request in different threads, each thread to complete, throw the result into a variable, or list ... according to my needs. Does anyone have a solution to help me?

Many thanks to all of StackOverflow users because they are helping me a lot.

Milton Câmara Gomes

mcamara
  • 731
  • 4
  • 15
  • 26

3 Answers3

1

It sounds to me like you want to perform an asynchronous request. There is a lot of information on this already (e.g. stackoverflow, official MSDN walkthrough and an MSDN blog posting).

Community
  • 1
  • 1
Justin Helgerson
  • 24,900
  • 17
  • 97
  • 124
  • Building on this answer, if you need to put things into some kind of a collection when the request returns, make sure to use a collection that's thread-safe such as those in System.Collections.Concurrent - http://msdn.microsoft.com/en-us/library/dd287108.aspx Alternatively, if you know the number of requests you're firing off you could allocate an array of that size, which would be thread-safe as long as each time the response was handled a different index of the array was written to. – Zann Anderson Oct 21 '11 at 18:28
0

The usual answer is threading. Instead of running each individual request and waiting for the response, you can make each request on its own thread and then return when all the threads have received their result. This allows you to overlap a considerable amount of the time spent waiting for the other services to execute.

If you're using .NET 4, try the TPL's Parallel.ForEach() method. It allows you to specify that a particular operation should be performed on each item of a collection, with similar functionality to the built-in foreach keyword. It sounds like it should "drop in" pretty easily to the code you're using right now. Documentation here: http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.foreach.aspx.

KeithS
  • 70,210
  • 21
  • 112
  • 164
0
List<...> requests = new List<...>();
List<...> results = new List<...>();
Parallel.ForEach(requests,request=>{
    var res = DoWork(request);
    lock (results) results.Add(res);
});
L.B
  • 114,136
  • 19
  • 178
  • 224
  • You may want to use a ConcurrentBag rather than a List. The Concurrent Collections take care of concurrency issues for you: http://msdn.microsoft.com/en-us/library/dd381779.aspx – Mathias Oct 21 '11 at 18:38