Is Thread.Sleep(Timeout.Infinite); more efficient than while(true){}?

前端 未结 6 857
Happy的楠姐
Happy的楠姐 2020-12-09 02:46

I have a console application that I would like to keep open all of the time while still listening in to events. I have tested Thread.Sleep(Timeout.Infinite); an

6条回答
  •  情话喂你
    2020-12-09 03:17

    Since C# 7.1, you can make the Main method asynchronous. That means instead of using busy-wait or thread-locking sleeping, you can suspend the Main method asynchronously as a Task. This way, the thread which ran Main will not be locked. And with Cts.Cancel(), you can easily release the main task to exit the application (without allowing work for other threads/tasks to finish).

    static readonly CancellationTokenSource Cts = new CancellationTokenSource();
    static async Task Main(string[] args)
    {
        /* your code here */
    
        // Task running Main is efficiently suspended (no CPU use) forever until Cts activated with Program.Cts.Cancel(); (thread-safe) from anywhere.
        await Task.Delay(Timeout.Infinite, Cts.Token).ConfigureAwait(false);
    }
    

    Since year 2020, C# 9.0, the whole Program.cs file content can literally look exactly like this:

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    
    static readonly CancellationTokenSource Cts = new CancellationTokenSource();
    
    /* your code here */
    
    // Task running Main is efficiently suspended (no CPU use) forever until
    // Cts activated with Program.Cts.Cancel(); (thread-safe) from anywhere.
    await Task.Delay(Timeout.Infinite, Cts.Token).ConfigureAwait(false);
    

提交回复
热议问题