C#如何暂停计时器? [英] C# How to pause a timer?

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

问题描述

我有一个C#程序,如果用户停止与该程序的交互,我需要计时器停止.它需要做的是暂停,然后在用户再次变为活动状态时重新启动.我进行了一些研究,发现其中包含以下命令:

I have a C# program in which, I need the timer to stop if the user stops interacting with the program. What It needs to do is pause, and then restart when the user becomes active again. I have done some research, and found that there is commands such as:

timer.Stop(); 

timer.Start();

但是我想知道是否有这样的东西:

But I was wondering if there was like a:

timer.Pause();

然后,当用户再次变为活动状态时,它将从上次中断的地方开始,并且不会重新启动.如果有人可以提供帮助,将不胜感激!谢谢,

And then when the user becomes active again, it picks up where it left off, and doesn't restart. If anyone can help, it would be much appreciated! Thanks,

弥迦

推荐答案

您可以通过使用.NET中的 Stopwatch 类来实现此目的.通过简单地停止和启动,您可以继续使用秒表实例.

You achieve this by using the Stopwatch class in .NET. By simply stopping and starting you continue the use of the instance of the stopwatch.

确保通过System.Diagnostics使用;

Make sure to make use of using System.Diagnostics;

var timer = new Stopwatch();
timer.Start();
timer.Stop();
Console.WriteLine(timer.Elapsed);

timer.Start(); //Continues the timer from the previously stopped time
timer.Stop();
Console.WriteLine(timer.Elapsed);

要重置秒表,只需调用 Reset Restart 方法,如下所示:

To reset the stopwatch, just call the Reset or Restart methods, like below:

timer.Reset();
timer.Restart();

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

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