Reputation: 3942
I'm want to make multiple requests to a remote service and I'm trying an asynchronous/multithread approach. For the concurrent part, I'll try this http://coding-time.blogspot.pt/2008/03/implement-your-own-parallelfor-in-c.html
IList<string> returnedValues = new List<string>();
int numberOfRequests = 5;
object sync = new object();
ParallelUtilities.For(0, numberOfRequests, delegate(int i)
{
string response = string.Empty;
try
{
try
{
Func<int, string> caller = CallService;
IAsyncResult result = caller.BeginInvoke(i, null, null);
Thread.Sleep(0);
string returnValue = caller.EndInvoke(result);
lock (sync)
{
returnedValues.Add(returnValue);
}
}
catch (Exception ex)
{
Console.WriteLine(string.Concat("ex: ", ex.Message, "stack:", ex.StackTrace));
}
});
}
And the service call
private string CallService(int index)
{
string value;
using (var channel = GetClientChannel<IService>("http://localhost:51383/Service/Service.svc"))
{
value = channel.GetValue(index);
}
return value + "for this index:" + index;
}
Is there a better way to do this? How do IAsyncResult works in multithreading?
Upvotes: 0
Views: 119
Reputation: 171178
Replace
IAsyncResult result = caller.BeginInvoke(i, null, null);
Thread.Sleep(0);
string returnValue = caller.EndInvoke(result);
with
string returnValue = CallService(result);
There's no point in starting code on the thread-pool and then waiting for it immediately. What would you gain by doing that? The Sleep
is especially suspicious to me. You try to initiate a context switch which just adds additional overhead.
How do IAsyncResult works in multithreading?
The two are not related. What do you mean?
Upvotes: 2