c#进程线程写计时器
时间: 2023-07-04 12:27:35 浏览: 66
你可以使用C#的System.Diagnostics和System.Threading命名空间来编写一个计时器。
首先,你需要创建一个计时器类,它将继承System.Timers.Timer类,并实现计时器的逻辑。下面是一个简单的计时器类示例:
```csharp
class MyTimer : System.Timers.Timer
{
private int _count;
public MyTimer(int interval)
{
Interval = interval;
AutoReset = true;
Elapsed += OnElapsed;
}
private void OnElapsed(object sender, ElapsedEventArgs e)
{
_count++;
Console.WriteLine($"Timer tick {_count}");
}
}
```
该类接受一个间隔参数,并在每个时间间隔上触发Elapsed事件,并输出计时器已经运行的秒数。
接下来,在你的应用程序中创建一个MyTimer对象并启动它。下面是一个简单的控制台应用程序示例:
```csharp
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
var timer = new MyTimer(1000);
timer.Start();
Console.WriteLine("Press enter to stop the timer.");
Console.ReadLine();
timer.Stop();
}
}
```
该应用程序创建了一个MyTimer对象,并在控制台上输出计时器的运行情况。它还等待用户按Enter键来停止计时器。
注意:在使用计时器时,你需要确保线程安全。例如,你可以使用System.Threading.Interlocked类来原子地增加计数器的值。