Reputation: 33857
I have code similar to the following pseudo code:
static int counter;
function GetCalculations()
{
for (x service calls)
{
service.BeginCalc(MyCallback);
Interlocked.Increment(counter);
}
while(counter > 0)
{
//Wait for all results to return
}
return;
}
static function MyCallback()
{
try
{
... process results
}
finally
{
Interlocked.Decrement(counter);
}
}
My question is in relation to the wait in the above code (the while (counter > 0)). Is this going to be a performance issue? I know that the multiple calls that I am making (to remote web services) take at least a few seconds to return - would I be better introducing something like a Thread.Sleep() in the while loop so that I am only checking for all returned every quarter second or so?
My gut instinct is that putting thread sleeps into my code smells a bit, but I'm just not well enough versed in this kind of code to say one way or the other.
Upvotes: 1
Views: 283
Reputation: 2136
You could use task parallel library. It has easy to use mechanisms to wait on Tasks
Below is an example from MSDN
Task[] tasks = new Task[3]
{
Task.Factory.StartNew(() => MethodA()),
Task.Factory.StartNew(() => MethodB()),
Task.Factory.StartNew(() => MethodC())
};
//Block until all tasks complete.
Task.WaitAll(tasks);
Upvotes: 3
Reputation: 1598
If you're on .NET 4 you could, as has been mentioned, use the TPL (Task Parallel Library).
Otherwise, you have Reactive Extensions (Rx.NET), which is also built to compose asynchronous operations together
If you don't want to use any third party library at all, you could create a bunch of ManualResetEvent instances, which you can then wait for using the WaitAll static method.
Upvotes: 0
Reputation: 1151
I'm not sure what the point of having the async calls would be if you're just going to block until they return. Sounds like you've got GetCalculations() being called from another function that needs the results before it can proceed. Instead of blocking the thread, what about moving the dependent code to its own function? Then call that function in your callback. If you need to make sure all the callbacks are finished, you can just check the counter in the callback function before you call the function that contains the dependent code.
Upvotes: 2