C#之下如何做定时

先如下定义一个定时器:

public DispatcherTimer dispatcherTimer;

然后在某处创建这个对象实例:

dispatcherTimer = new System.Windows.Threading.DispatcherTimer();

设定超时回调函数:

dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);

设定间隔(下方例子是10秒钟):

dispatcherTimer.Interval = new TimeSpan(0, 0, 10);

启动定时器:

dispatcherTimer.Start();

定义超时回调函数:

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// do something here...
}

值得注意的是DispatcherTimer是无法直接在console下运行的,需要额外的东西。

下面文字来自http://stackoverflow.com/questions/19351473/dispatchertimer-doesnt-work-in-console的解释

The console and unit test environment by default don't have a dispatcher to run your dispatcher timer.

You can still use Dispatcher.CurrentDispatcher to create a Dispatcher to run your code.

本文来自本人的51cto上的博文:点击打开链接


猜你喜欢

转载自blog.csdn.net/qq_16587307/article/details/79620825