Asynchronous tasks, waiting in main thread for completition

最后都变了- 提交于 2019-12-13 10:19:57

问题


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.

Example: http://pastebin.com/uhBGWC5e

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

More specifically, the "while" loop.

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.

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).

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?


回答1:


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

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.




回答2:


The simple solution is to use Thread.Sleep(1000) in the main thread loop.

You could also mark your tasks as foreground threads. An application is kept alive while all foreground threads are alive. Read more about foreground and background threads here. Also take a look at this question on how to make a task a foreground thread.



来源:https://stackoverflow.com/questions/23931937/asynchronous-tasks-waiting-in-main-thread-for-completition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!