Search code examples
winapic#-4.0timerpinvoke

System does not sleep after restoring the default settings using SetThreadExecutionState


I created a method to prevent the system from sleeping as follows:

    public static void KeepSystemAwake(bool bEnable)
    {
        if (bEnable)
        {
            EXECUTION_STATE state = SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
        }
        else
        {
            EXECUTION_STATE state = SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
        }
    }

The method prevents the system from sleep but when I call the ES_CONTINUOUS part of the method,the system does not sleep at all when I want it behave normally. What am I missing? I'm running this code in a different thread (Timer)


Solution

  • I'm running this code in a different thread (Timer)

    If you're using something like a System.Threading.Timer callback, it will be called on different (read: arbitrary) threads.

    From MSDN:

    The callback method executed by the timer should be reentrant, because it is called on ThreadPool threads

    Make sure you're calling SetThreadExecutionState for the same thread. Ideally, you'll serialise calls onto one thread (like the main thread).