guogangj
guogangj

Reputation: 2435

System.Threading.Timer is not always called

I wrote a simple helper class for executing delay tasks:

public class TaskExecutor {
    private static void Callback(object state) {
        ((Action)state)(); //Not always be called
    }
    public static void DelayExecute(int mSec, Action task) {
        if (task != null) {
            new Timer(Callback, task, mSec, Timeout.Infinite);
        }
    }
}

I use it like this:

TaskExecutor.DelayExecute(10000, () => { Console.WriteLine("Haha..."); });

However, the timer does not seem to work everytime. That means sometimes it is fine and sometimes it is bad. Why? And how can I make it right?

Upvotes: 1

Views: 45

Answers (1)

Valery Petrov
Valery Petrov

Reputation: 673

You must have somewhere a reference to Timer object you created. Otherwise it will be collected by GC.

Upvotes: 1

Related Questions