¿Cómo realizar entrelazado. Incremento/disminución correctamente en IO Bound?

StackOverflow https://stackoverflow.com/questions/20353398

  •  25-08-2022
  •  | 
  •  

Pregunta

Tengo una aplicación simple de consola IO Bound 4.0, que envía 1 a N solicitudes a un servicio web y esperan su finalización y luego salga. Aquí hay una muestra,

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

¿Es esta es la implementación correcta?

¿Fue útil?

Solución 2

Según lo sugerido por Hans, aquí está su código implementado con CountdownEvent:

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

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

    counter.Wait();
}

Otros consejos

Puedes usar tareas. Deje que TPL maneje esas cosas.

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

Otra forma es usar TaskCompletTioSource como se menciona aquí.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top