Domanda

Ho una semplice applicazione della console IO Bound 4.0, che invia richieste da 1 a N a un servizio Web e attendo il loro completamento e poi esco. Ecco un campione,

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

È una corretta implementazione?

È stato utile?

Soluzione 2

Come suggerito da Hans, ecco il tuo codice implementato con CountdownEvent:

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

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

    counter.Wait();
}

Altri suggerimenti

Puoi usare le attività. Lascia che TPL gestisca queste cose.

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

Un altro modo è usare TaskCompletionSource come menzionato qui.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top