我有简单的IO绑定4.0控制台应用程序,该应用程序将1向N请求发送到Web服务,并等待其完成然后退出。这是一个样本,

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