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

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

问题描述

我已经为此任务设置了非常详细的示例,可能在体系结构和一些 .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

这里有问题的代码是 Main 方法:

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.ReadKeyConsole.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?

推荐答案

尝试使用以下代码:

    ...

    // 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.但是您必须实现 Accept 以便它阻塞直到应用程序终止.

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.

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

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