Waiting for multiple asynchronous POST requests

I need to make some asynchronous calls inside a wcf service hosted in IIS (maybe I don't know). Calls relate to other services, but I do them by POSTing a string to the service url. Calling them synchronously works, but I have more than a dozen calls, and they are completely independent, so I would like to speed them up by calling them asynchronously.

Now I understand that I could just use multiple threads for this - and that might be the easiest solution, but I thought I would give an asynchronous try.

My code is similar to this:

public delegate void Callback(string response); public static void InvokeAsync(string request, string url, Callback callback) where TResponse: class { var web = new WebClient(); web.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); web.UploadStringCompleted += (sender, e) => callback.Invoke(e.Result); web.UploadStringAsync(new Uri(url), request); } //... var lockObj = new object(); foreach (var item in list) InvokeAsync(item, url, response => { lock(lockObj) newList.Add(response); }); 

The above should work, I suppose; however, my problem is that I do not know how to wait until all the answers come back. If I use a counter and wait in a loop until it becomes zero, the processor will not be processed for callbacks. I suppose using some form of semaphore. Is there a non-blocking way to wait until I get all the answers back? I'm afraid that changing the method signature will also lead to a callback, only the problem will be raised one level.)

[Edit] Here is a very close question - How to call the async operation as synchronization? - but I need to wait for several asynchronous operations.

+6
c # asynchronous webclient
source share
2 answers

For this, AutoResetEvent used.

Try the following for the last two lines:

 var waitEvent = new AutoResetEvent(false); foreach (var item in list) InvokeAsync(item, url, response => { lock(lockObj) newList.Add(response); waitEvent.Set(); }); while (newList.Count < list.Count) waitEvent.WaitOne(); 

All items must be filled when newList contains as many items as list . When a new element appears, you add it to newList . Then you tell waitEvent that "something" happened with newList .

In the main thread, you just wait until you have enough elements in newList , and you wait for this, waiting for the changes to newList that waitEvent reports.

+3
source share

According to the HTTP protocol, the client can open only 2 connections to the service.

0
source share

All Articles