简体   繁体   English

哪个C#计时器?

[英]Which C# Timer?

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. 我正在编写一个包含计时器的类(至关重要的是,该计时器可能未初始化为0,它可能已经开始运行),并且该类将包含Start,Pause,Resume和Stop / Complete的方法。 I'm aware of a number of timers in C# that I can use, ie System.Timers.Timer, however I'm not sure if this one lets me start the timer at a predefined elapsed figure. 我知道我可以使用C#中的许多计时器,即System.Timers.Timer,但是我不确定这是否可以让我以预定义的运行时间启动计时器。

What is the best for this scenario? 在这种情况下最好的是什么?

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.Windows.Forms.Timer这将在窗体的UI线程上运行委托,这可能不是您想要的。

System.Timers.Timer derives from System.ComponentModel.Component , and so its geared towards a design surface. System.Timers.Timer派生自System.ComponentModel.Component ,因此其面向设计图面。

System.Threading.Timer is best for background tasks on a thread pool. System.Threading.Timer最适合线程池上的后台任务。

System.Threading.Timer satisfies all your requirements (assuming you're trying to run delegates on the threadpool. System.Threading.Timer满足您的所有要求(假设您正在尝试在线程池上运行委托。

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();

Use System.Timers.Timer . 使用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. 根据您的间隔,您可以将计时器间隔设置为1秒(或10,或1分钟),并检查每次是否经过您自己的经过条件。 Basically you are checking yourself if you need to do something. 基本上,您是在检查自己是否需要做某事。 And this way, you can start a certain period 'into' the interval. 这样,您就可以开始一定的时间间隔。

System.Forms.Timer class is used really for the UI end and less accurate & optimized than System.Timers.Timer class. System.Forms.Timer类实际上用于UI端,并且不如System.Timers.Timer类准确和优化。

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. Forms.Timer在UI线程(主线程)上运行,因此UI任务花费时间,并且Timer类在不同的线程上运行,导致主线程上没有负载。

Timers.Timer class also has all the events that you want, check out below links for more details on events Timers.Timer类还具有所需的所有事件,请查看以下链接以获取有关事件的更多详细信息

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM