如何在C#中设置计时器?

Han*_*ang 0 c# xaml timer windows-8.1

在C#中,我想在进入页面时设置一个计时器,然后开始倒计时十秒钟.

如果用户未在十秒内完成操作,则触发计时器,提示"游戏结束".

如果用户在十秒内完成操作,则取消定时器设备.

我怎样才能做到这一点?

Kar*_*nth 7

使用DispatcherTimer课程.该tick事件处理程序应该有,说这款游戏的代码.

示例:

DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0,0,10);
dispatcherTimer.Start();

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    ((DispatcherTimer)sender).Stop();
    //Your code here
}
Run Code Online (Sandbox Code Playgroud)

只要用户刚完成操作,您就可以打电话dispatcherTimer.Stop();.这将停止计时器.