C# prevent pc sleeping escepially for long running task via invoking SetThreadExecutionState from kernel32.dll
using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace ConsoleApp10 { internal class Program { [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags); [FlagsAttribute] public enum EXECUTION_STATE : uint { ES_AWAYMODE_REQUIRED = 0x00000040, ES_CONTINUOUS = 0x80000000, ES_DISPLAY_REQUIRED = 0x00000002, ES_SYSTEM_REQUIRED = 0x00000001 // Legacy flag, should not be used. // ES_USER_PRESENT = 0x00000004 } static UInt128 num = 0; static void Main(string[] args) { SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_SYSTEM_REQUIRED | EXECUTION_STATE.ES_DISPLAY_REQUIRED); while (true) { Console.WriteLine($"{++num},{Guid.NewGuid().ToString("N")}"); } } } }