Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...