异步任务,在completition主线程等待 [英] Asynchronous tasks, waiting in main thread for completition

查看:296
本文介绍了异步任务,在completition主线程等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了相当详细的例子完成这个任务,可以写在建筑和一些.NET使用方面差强人意,但我刚刚开始。

I have set up quite detailed example for this task, it may be poorly written in terms of architecture and some .NET usage, but I'm just starting.

例如: http://pastebin.com/uhBGWC5e

在code那就是这里的问题,是主要的方法:

The code that is of problem here, is the Main method:

public static void Main (string[] args)
{
    Log("Initializing...");

    // Define listeners.
    TcpListener s1 = CreateAndStartServer(IPAddress.Any, 1337);
    TcpListener s2 = CreateAndStartServer(IPAddress.Any, 1338);

    // Start async.
    Task.Factory.StartNew(Accept, s1);
    Task.Factory.StartNew(Accept, s2);

    // Wait for connections only if servers active.
    while (servers.Any(s => s.Key.Active))
    {
        // 100% usage.
    }

    Log("Nothing left to do, stopping service.");
}

更具体地,while循环

More specifically, the "while" loop.

我想在这里做的,就是,我创建和启动了一些TCP监听器,并将它们添加到列表中。

What I'm trying to do here, is, that I create and start some TCP Listeners, and add them to a list.

然后,服务器本身有一个允许远程合闸的实现。

Then, the servers themselves have an implementation that allow remote closing.

循环是有检查程序有一些工作要做。如果没有什么剩下要做的,就应该退出。 (将来时,我会得到实际执行,会有沿着TCP监听UDP一些的人,任务队列,计时器等等,所有将等待完成)。

The loop is there to check if the program has some work to do. In case there is nothing left to do, it should quit. (In future when I'll get to actual implementation, there will be along TCP listeners some UDP ones, task queues, timers etc. that all will be waited for completion).

问题是,while循环导致100%的使用率 - 它提供的功能,但它消耗太多。我可以用 Console.ReadKey 到Console.ReadLine 取代它,但是这不是我要找的行为。

The problem is, that the while loop is causing 100% usage - it provides the functionality, but it does consume too much. I can replace it with Console.ReadKey or Console.ReadLine, but that's not the behavior I'm looking for.

什么其他选择在那里等待没什么可做状态?

What other options are there to wait for "nothing left to do" state?

推荐答案

尝试使用这种code:

Try using this code:

    ...

    // Start async.
    var task1 = Task.Factory.StartNew(Accept, s1);
    var task2 = Task.Factory.StartNew(Accept, s2);

    Task.WhenAll(task1, task2).Wait();    

    Log("Nothing left to do, stopping service.");
}

这也应该这样做,但不要使用100%的CPU。但是,你必须实现接受使其阻塞,直到应用程序应该终止。

This should do the same but not use 100% CPU. But you have to implement Accept so that it blocks until the application should terminate.

这篇关于异步任务,在completition主线程等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆