其中C#计时器? [英] Which C# Timer?

查看:140
本文介绍了其中C#计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个类,其中将包括一个定时器(关键可能不是0被初始化,它可能会开始已经过去了),类包括的方法开始,暂停,恢复和停止/完成。我所知道的多个定时器在C#中,我可以使用,即System.Timers.Timer的,然而我不知道,如果这一个让我开始计时以predefined逝去的身影。

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?

推荐答案

不使用的 System.Windows.Forms.Timer - 这一次将上运行的代理形式的UI线程,这可能不是你想要的。

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的 System.ComponentModel.Component ,因此它着眼于设计图面。

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

System.Threading.Timer 是最好的一个线程池后台任务。

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.

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

这篇关于其中C#计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆