Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

c# - Asynchronous tasks, waiting in main thread for completition

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...