How to call of SetThreadExecutionState correctly?

Viewed 251

The following snippet is supposed to prevent a Windows machine to go to sleep while an important operation is finished (running a different thread):

[Flags]
private enum EXECUTION_STATE : uint
{
    ES_AWAYMODE_REQUIRED = 0x00000040,
    ES_CONTINUOUS = 0x80000000,
    ES_DISPLAY_REQUIRED = 0x00000002,
    ES_SYSTEM_REQUIRED = 0x00000001
}

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

public async Task KeepAwakeAsync(CancellationToken cancellationToken = default) 
{
  while (!cancellationToken.IsCancellationRequested)
    var result = SetThreadExecutionState(EXECUTION_STATE.ES_SYSTEM_REQUIRED); // (XXX)
    if (result == 0)
    {
      throw new InvalidOperationException("SetThreadExecutionState failed.");
    }

    await Task.Delay(TimeSpan.FromMinutes(1)).ConfigureAwait(false);
  }
}
  1. I'm not sure whether ES_CONTINUOUS is needed too (i.e. var result = SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_SYSTEM_REQUIRED);).

    Can anyone explain the difference between ES_CONTINUOUS | ES_SYSTEM_REQUIRED and ES_SYSTEM_REQUIRED when used in the sample above?

  2. I read somewhere that SetThreadExecutionState applies only to the current thread. Is that true? Can anybody elaborate on the precise meaning?

I have read [1] and for some reason it confuses me every time I read it.

Resources:

0 Answers
Related