Click here to Skip to main content
15,891,785 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello.

I am making a algorithm that checks if a a device is started or not.
The idea is that I make timer and initialize it, checking every 1,5 sec.

C#
private Timer timerChecker = new Timer();

timer.Tick += this.OnCheck();

private bool isStarted = true;
private bool isStopped = true;

private void OnCheck()
{
    var process = Process.GetProcessByName("processname");
    

if(process.Lenght > 0)
{
    if(!isStarted)
    {
        device.Start();//Start the device, sometimes it starts two times, which is not good
        isStarted = true;
        isStopped= false;
    }
}
else
{
    if(!isStopped) 
    {
        device.Stop(); // Stop the device
        
        isStarted = true;
        isStopped= false;
    }
}

}


Can you offer me better way to check this thing.
Posted

1 solution

First, every time it executes OnCheck you should disable the timer, to avoid a second call while starting/stooping, and enable it before exit the method.

private void OnCheck()
{
    timerChecker.Enabled = false;

    // Do things...


    timerChecker.Enabled = true;
}


It's not clear to me when isStarted/isStoped change it value, I understand it as MustStart & MustStop. If not, simply start/stop the process alternatively.

You could use one variable only for this function.
 
Share this answer
 
Comments
Zhivko Kabaivanov 18-Mar-15 22:35pm    
The concept is that when the device is started, if a certan process is running to stop the device and vice versa - device - stoped, if process is not running, to start device.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900