Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

485
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda