Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

497
Visualizações
How to call of SetThreadExecutionState correctly?

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:

  • [1] https://docs.microsoft.com/en-gb/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate
  • [2] Prevent screen from sleeping with C#
  • [3] SetThreadExecutionState is not working when called from windows service
over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda