Question

I have simple IO bound 4.0 console application, which send 1 to n requests to a web-service and wait for their completion and then exit. Here is a sample,

static int counter = 0;
static void Main(string[] args)
{
foreach (my Loop)
{
    ......................
    WebClientHelper.PostDataAsync(... =>
    {

        ................................
        ................................
        Interlocked.Decrement(ref counter);
    });
    Interlocked.Increment(ref counter);
}
    while(counter != 0)
    {
    Thread.Sleep(500);
    }
}

Is this is correct implementation?

Was it helpful?

Solution 2

As suggested by Hans, here's your code implemented with CountdownEvent:

static void Main(string[] args)
{
    var counter = new CountdownEvent();
    foreach (my Loop)
    {
        ......................
        WebClientHelper.PostDataAsync(... =>
        {

            ................................
            ................................
            counter.Signal();
        });
        counter.AddCount();
    }

    counter.Wait();
}

OTHER TIPS

You can use Tasks. Let TPL manage those things.

Task<T>[] tasks = ...;
//Started the tasks
Task.WaitAll(tasks);

Another way is to use TaskCompletionSource as mentioned here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top