SetThreadExecutionState is not working when called from windows service

六月ゝ 毕业季﹏ 提交于 2020-01-01 04:49:25

问题


I want prevent system from going to sleep/hibernate from a windows service. I am calling SetThreadExecutionState function to do that. But it seems to have no effect. I just want to know whether the function SetThreadExecutionState will for windows services. If not what will be the alternative ways to that.

Below is the C# code i am using. I am calling it on Onstart method of service.

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern uint SetThreadExecutionState(EXECUTION_STATE esFlags);
private void KeepAlive() 
{
     SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_SYSTEM_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS)
}

回答1:


Calling SetThreadExecutionState without ES_CONTINUOUS simply resets the idle timer; to keep the display or system in the working state, the thread must call SetThreadExecutionState periodically.

(source)

You need to call this function every now and then. It's not a fire-and-forget.




回答2:


SetThreadExecutionState is only valid for the thread that calls it. If it's called in a worker thread, even with ES_CONTINUOUS, once the worker thread is dead, the setting is not valid anymore and then screen saver will be on again.

Calling this API from a Timer will wake up a worker thread before previous thread is dead and therefore makes it work.

So if you call SetThreadExecutionState in your main thread, like UI thread in client applications, you don't need timer.



来源:https://stackoverflow.com/questions/5870280/setthreadexecutionstate-is-not-working-when-called-from-windows-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!