c# – Preventing the system from falling asleep and falling asleep problems

Question:

The essence of the task:

For some time, it is necessary to keep the system in a working state, not allowing it to go into standby mode. To do this, I periodically (fortunately, there is a method that is executed once every 30 seconds), I call the WinApi function:

EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags)

with flags ES_DISPLAY_REQUIRED and ES_DISPLAY_REQUIRED

Here is a listing of the application in which I managed to manifest this problem:

namespace ConsoleApplication7
{
    class Program
    {
        private static void KeepAlive()
        {
            Win32.SetThreadExecutionState(
                Win32.EXECUTION_STATE.ES_DISPLAY_REQUIRED |
                Win32.EXECUTION_STATE.ES_SYSTEM_REQUIRED);
        }

        static void Main(string[] args)
        {
            SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;

            for (int i = 0; i < 1; i++)
            {
                Thread.Sleep(50 * 1000);
                Console.WriteLine("Timer resetted: " + DateTime.Now);
                KeepAlive();
            }
            Console.ReadKey();
        }

        private static void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
        {
            Console.WriteLine("power mode changed to: " + e.Mode);
        }
    }

    static class Win32
    {
        [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
        }

        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);

    }
}

The sleep timer is set to 1 minute.

When this application is executed, the following picture is obtained: The application is launched, after 50 seconds the function is called and the system continues to work for another 1 minute without going into sleep mode. After this minute, the monitor turns off, but the system does not enter standby mode.

Questions: Why doesn't the system go to sleep when the timer expires?

How to make the system fall asleep during application execution after the idle timer expires?

Answer:

The problem was not in the application, but in setting the computer's power mode. Thank you all for your interest.

Scroll to Top