Question

J'ai une application de console IO Bound 4.0 simple, qui envoie 1 à N demandes à un service Web et attendez leur achèvement puis sortez. Voici un échantillon,

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);
    }
}

Est-ce une implémentation correcte?

Était-ce utile?

La solution 2

Comme suggéré par Hans, voici votre code implémenté avec CountdownEvent:

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

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

    counter.Wait();
}

Autres conseils

Vous pouvez utiliser des tâches. Laissez TPL gérer ces choses.

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

Une autre façon consiste à utiliser TaskCompletionsource comme mentionné ici.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top