4

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:

Kiminuo
  • 41
  • 3
  • 1
    1: It is not needed since the code calls it repeatedly. 2: The ConfigureAwait() call prevents the use of ES_SYSTEM_REQUIRED, the thread that turns it on must be the same thread that turns it off. – Hans Passant Jul 07 '21 at 12:32
  • `while (cancellationToken.IsCancellationRequested)` looks wrong - it'll only loop if cancellation has already been requested and I don't think you can "un-cancel" a cancellationToken. – Damien_The_Unbeliever Jul 07 '21 at 13:13
  • @HansPassant: So now I understand that one should not use `ConfigureAwait(false)` but what happens when it it actually used? I basically set for *different* threads that they should not sleep, right? @Damien_The_Unbeliever: Yes, I fixed it. Thank you. – Kiminuo Jul 07 '21 at 15:43

0 Answers0