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); }
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.
c # asynchronous webclient
Marcel popescu
source share