C# 三种计时器的对比
时间: 2023-11-23 19:46:23 浏览: 46
在C#中,有三种常用的计时器:Timer控件、System.Timers.Timer类和System.Threading.Timer类。
Timer控件是在System.Windows.Forms命名空间下的,直接继承自Component类。它需要绑定Tick事件,并设置Enabled=True后才会自动计时。可以使用Stop()方法停止计时,使用Start()方法重新启动计时器。Timer控件和它所在的Form处于同一个线程。
System.Timers.Timer类是在System.Timers命名空间下的。使用该类时,需要定义一个System.Timers.Timer对象,并绑定Elapsed事件。通过Start()方法启动计时,通过Stop()方法或Enable=false停止计时。可以设置AutoReset属性来决定是否重复计时。Elapsed事件绑定会创建一个新的线程,在该线程中无法访问其他线程中的控件。
System.Threading.Timer类也是一种常用的计时器。在定义该类时,需要通过构造函数进行初始化。它会创建一个新的线程来执行计时逻辑。
总的来说,Timer控件适用于在UI线程中执行计时操作,System.Timers.Timer类和System.Threading.Timer类适用于在独立的线程中执行计时操作。
相关问题
c#timer 计时器
在C#中,有多种计时器可供使用,包括Timer、System.Timers.Timer、System.Threading.Timer和DispatcherTimer。其中,Timer是Windows.Forms.Timer的别名,而System.Timers.Timer和System.Threading.Timer都是基于线程的计时器。下面是一个使用Timer计时器的例子:
```csharp
using System;
using System.Windows.Forms;
public class TimerExample : Form
{
private Timer timer1;
public TimerExample()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000; // 1 second
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
// 在这里编写每秒执行的代码
}
static void Main()
{
Application.Run(new TimerExample());
}
}
```
在上面的例子中,我们创建了一个名为timer1的计时器,并将其Interval属性设置为1000毫秒(即1秒)。然后,我们订阅了timer1的Tick事件,并在事件处理程序中编写了每秒执行的代码。最后,我们在Main方法中启动了应用程序并显示了窗体。
c# 计时器显示
在 C# 中使用计时器可以显示时间,可以使用 Timer 控件实现。以下是一个简单的示例代码:
```csharp
using System;
using System.Windows.Forms;
namespace TimerDemo
{
public partial class Form1 : Form
{
private Timer timer;
private int count;
public Form1()
{
InitializeComponent();
timer = new Timer();
timer.Interval = 1000; // 每隔1秒触发一次
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
count++;
label1.Text = TimeSpan.FromSeconds(count).ToString(); // 将秒数转换为时间格式显示在 label 控件上
}
}
}
```
在窗体的构造函数中创建一个 Timer 控件,并设置其间隔为 1 秒。在 Tick 事件中,每次计时器触发时增加计数变量 count 的值,然后将其转换为时间格式并显示在 label1 控件上。