TheGateKeeper
TheGateKeeper

Reputation: 4540

Preventing A Thread From Ending

I understand that a Thread will terminate when all of the code it has been assigned is done, but how can I make it so that it stays around waiting for an event? Here is a simple look at my code so you can understand better what my problem is:

public static class TimeUpdater
{

        static TimeUpdater()
        {
            //Initialize the Timer object
            timer = new Timer();
            timer.Interval = 1000; 
            timer.Tick += timer_Tick;
        }

        public static void StartTimer()
        {
            timer.Start();
        }

        private static void timer_Tick(object sender, EventArgs e)
        {
            //Do something          
        }

}

From the main Thread, here is how I am calling these methods:

        Thread timeThread = new Thread(TimeUpdater.StartTimer);
        timeThread.Name = "Time Updater";

        timeThread.Start();

What this does is it goes inside the StartTimer() method, runs it, and then the thread terminates without ever entering the timer_Tick event handler. If I call StartTimer() from the main thread it works fine.

Anyone can spot the problem? Cheers.

Upvotes: 1

Views: 68

Answers (3)

Brian Gideon
Brian Gideon

Reputation: 48959

In your StartTimer method you can spin around an infinite loop and call Thread.Sleep to delay execution when needed. I see you have already figured that out though. An alternate idea is to use a timer, but instead of starting it from a worker thread start it from the main thread. You really do not need to be manually creating threads at all here.

Upvotes: 0

TheGateKeeper
TheGateKeeper

Reputation: 4540

Apparently I didn't need to use a Timer object. Here is how I made it work:

    public static void StartTimer()
    {
        while (true)
        {
            UpdateTime();
            Thread.Sleep(1000);
        }
    }

Thanks for the help guys!

Upvotes: 1

usr
usr

Reputation: 171246

You are starting the timer on a separate thread. Starting a timer is a very fast operation. That's why your thread completes immediately. Tick events are started on the thread-pool asynchronously when the time is due.

If you want a thread wait for something then you should insert code into the thread procedure to wait on something. At the moment you do not wait for anything.

If you want to run the timer procedure, just call it.

Upvotes: 1

Related Questions