IO 바운드에서 연계/감소를 올바르게 수행하는 방법은 무엇입니까?

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

  •  25-08-2022
  •  | 
  •  

문제

간단한 IO Bound 4.0 콘솔 응용 프로그램이 있는데, 웹 서비스에 1 번의 요청을 보내고 완료를 기다린 다음 종료합니다. 다음은 샘플입니다.

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

이것이 올바른 구현입니까?

도움이 되었습니까?

해결책 2

Hans가 제안한대로 여기에 귀하의 코드가 구현되었습니다. CountdownEvent:

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

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

    counter.Wait();
}

다른 팁

작업을 사용할 수 있습니다. TPL이 그런 것들을 관리하도록하십시오.

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

또 다른 방법은 사용하는 것입니다 TaskCompletionSource 여기에 언급 된대로.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top