Which C# Timer?

2019-02-15 16:34发布

问题:

I'm writing a class that will include a timer (which crucially may not be initialized at 0, it may start already elapsed), and the class will include methods to Start, Pause, Resume and Stop/Complete. I'm aware of a number of timers in C# that I can use, i.e. System.Timers.Timer, however I'm not sure if this one lets me start the timer at a predefined elapsed figure.

What is the best for this scenario?

回答1:

Don't use System.Windows.Forms.Timer - This one will run the delegate on a form's UI thread, which is probably not what you want.

System.Timers.Timer derives from System.ComponentModel.Component, and so its geared towards a design surface.

System.Threading.Timer is best for background tasks on a thread pool.

System.Threading.Timer satisfies all your requirements (assuming you're trying to run delegates on the threadpool.

public void MyCallback(object o) { ... }
int timeToStart = 1000;
int period = 2000;

//fire the delegate after 1 second, and every 2 seconds from then on
Timer timer = new Timer(MyCallback, null, timeToStart, period);

//pause
timer.Change(Timeout.Infinite, Timeout.Infinite);

//resume
timer.Change(timeToStart, period);

//stop
timer.Dispose();


回答2:

System.Forms.Timer class is used really for the UI end and less accurate & optimized than System.Timers.Timer class.

Forms.Timer runs on the UI thread (main thread) hence UI task is takes time and Timer class runs on different thread causing no load on Main Thread.

Timers.Timer class also has all the events that you want, check out below links for more details on events

http://msdn2.microsoft.com/en-us/library/system.windows.forms.timer.aspx

http://msdn2.microsoft.com/en-us/library/system.timers.timer.aspx



回答3:

Use System.Timers.Timer.

Depending on your interval you can set the timer interval at 1 second (or 10, or at 1 minute), and check each time if your own elapsed condition is passed. Basically you are checking yourself if you need to do something. And this way, you can start a certain period 'into' the interval.



标签: c# .net timer