Search code examples
c#timercompact-framework

timer in console application


I am creating a device application using .NET compact framework 2.0. There is a system.threading.timer in my application which executes some code. It works fine. My problem is when I am running the app by double clicking on the exe in the bin folder, the timer starts and execute all it works but it never stops. It runs in the background even after closing the app by clicking the X-button or from the file menu close button. I don't understand how and where I stop or dispose of the timer so that it doesn't run after closing the app. May be something like a form_closing event in window form application. I had searched a lot in Google but did't find any proper answer.

The application is use to generate digital output for a device here is some code of timer event:

public static void Main()
{
   // Some code related to the device like open device etc
   // Then the timer
   System.Threading.Timer stt =
       new System.Threading.Timer(new TimerCallback(TimerProc), null, 1, 5000);
        Thread.CurrentThread.Join();
}

static void TimerProc(Object stateInfo)
{
    // It is my local method which will execute in time interval,
    // uses to write value to the device
    writeDigital(1, 0);

    GC.Collect();
}

It is working fine when I run the code in debug mode, timer stops when I stop the program. But not working when I run the exe.


Solution

  • You could create and dispose it in Main() and pass it to any methods that require it?

    private static void Main()
    {
        using (var timer = new System.Threading.Timer(TimerProc))
        {
            // Rest of code here...
        }
    }
    

    More importantly, this line of code:

    Thread.CurrentThread.Join();
    

    will never return, because you are asking the current thread to wait for the current thread to terminate. Think about that for a moment... ;)

    So your solution is probably to just remove that line of code.