iluomo
iluomo

Reputation: 151

How to prevent slowdown of portable C# process while user is away?

I wrote a C# program that runs in the background pretty much flawlessly, but it slows down if the machine is locked and left alone.

It turns an on-board LED on and off every 100 milliseconds, with the 100 milliseconds being timed by a "System.Threading.Thread.Sleep(100)" call. (This is for a headless system (no keyboard or monitor) that needs to blink to indicate various statuses.)

The problem comes when the system is left alone for a while and the desktop locks... the blinking stops... but if I come back to the machine and login (it's not headless right now) then the LED begins to ramp up and blink at full speed again.

I suspect that Windows might be doing some sort of power management scheme and slows down the process to conserve power(?).

To be clear, the device never enters a 'sleep' or 'hibernate' state, and the process returns to a normal cadence as soon as I log back in and move the mouse around for a second... The process is being run as the logged in user using admin rights.

Definitely no anti-virus on this machine. Resources being used (memory/CPU) are minuscule and basically equal before and after.

Does anyone know how to build or execute a C# process such that it remains running at a normal speed even if the user has locked the desktop and walked away for a few hours?

EDIT: Included Sample Code from Loop:

       while (true) {                

            foreach (var step in steps) 
            {
                var mode = step.Mode;
                var millis = step.Millis;
                switch (mode.ToUpper())
                {
                    //Set LED as per Mode Switch
                }
                System.Threading.Thread.Sleep(millis);
            }

            if (!loopForever) {
                //User wanted single pattern and then exit
                Environment.Exit(0);
            }
        }

Upvotes: 0

Views: 102

Answers (1)

Belurd
Belurd

Reputation: 782

We have solved this kind of issue on WPF application by using:

var executionState = NativeMethods.SetThreadExecutionState(EXECUTION_STATES.ES_CONTINUOUS | EXECUTION_STATES.ES_SYSTEM_REQUIRED);
NativeMethods.SetThreadExecutionState(executionState);

I hope it can help you. Here is more documentation

Upvotes: 0

Related Questions