CPU friendly infinite loop

前端 未结 11 1912
心在旅途
心在旅途 2020-12-04 09:15

Writing an infinite loop is simple:

while(true){
    //add whatever break condition here
}

But this will trash the CPU performance. This ex

11条回答
  •  Happy的楠姐
    2020-12-04 09:33

    It sounds to me like you want Main() to enter an interruptable loop. For this to happen, multiple threads must be involved somewhere (or your loop must poll periodically; I am not discussing that solution here though). Either another thread in the same application, or a thread in another process, must be able to signal to your Main() loop that it should terminate.

    If this is true, then I think you want to use a ManualResetEvent or an EventWaitHandle . You can wait on that event until it is signalled (and the signalling would have to be done by another thread).

    For example:

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace Demo
    {
        class Program
        {
            static void Main(string[] args)
            {
                startThreadThatSignalsTerminatorAfterSomeTime();
                Console.WriteLine("Waiting for terminator to be signalled.");
                waitForTerminatorToBeSignalled();
                Console.WriteLine("Finished waiting.");
                Console.ReadLine();
            }
    
            private static void waitForTerminatorToBeSignalled()
            {
                _terminator.WaitOne(); // Waits forever, but you can specify a timeout if needed.
            }
    
            private static void startThreadThatSignalsTerminatorAfterSomeTime()
            {
                // Instead of this thread signalling the event, a thread in a completely
                // different process could do so.
    
                Task.Factory.StartNew(() =>
                {
                    Thread.Sleep(5000);
                    _terminator.Set();
                });
            }
    
            // I'm using an EventWaitHandle rather than a ManualResetEvent because that can be named and therefore
            // used by threads in a different process. For intra-process use you can use a ManualResetEvent, which 
            // uses slightly fewer resources and so may be a better choice.
    
            static readonly EventWaitHandle _terminator = new EventWaitHandle(false, EventResetMode.ManualReset, "MyEventName");
        }
    }
    

提交回复
热议问题