用C#做一个毫秒级别的定时器,能准群的实现每40MS调用一个函数?

2024-11-25 13:48:05
推荐回答(3个)
回答1:

哈哈 尺有所短啊

我用的一个

public class Counter
{
long elapsedCount = 0;
long startCount = 0;

///


/// Start timing
///

public void Start()
{
startCount = 0;
QueryPerformanceCounter(ref startCount);
}

///
/// Stop timing
///

public void Stop()
{
long stopCount = 0;
QueryPerformanceCounter(ref stopCount);

elapsedCount += (stopCount - startCount);
}

///
/// Clear the timer
///

public void Clear()
{
elapsedCount = 0;
}

///
/// The elapsed time measured in seconds.
///

public float Seconds
{
get
{
long freq = 0;
QueryPerformanceFrequency(ref freq);
return ((float)elapsedCount / (float)freq);
}
}

///
/// The elapsed time measured in milliseconds.
///

public float Milliseconds
{
get
{
return Seconds * 1000;
}
}

///
/// Convert to a string
///

/// The current elapsed time in seconds
public override string ToString()
{
return String.Format("{0} seconds", Seconds);
}

static long Frequency
{
get
{
long freq = 0;
QueryPerformanceFrequency(ref freq);
return freq;
}
}

static long Value
{
get
{
long count = 0;
QueryPerformanceCounter(ref count);
return count;
}
}

[System.Runtime.InteropServices.DllImport("KERNEL32")]
private static extern bool QueryPerformanceCounter(ref long
lpPerformanceCount);

[System.Runtime.InteropServices.DllImport("KERNEL32")]
private static extern bool QueryPerformanceFrequency(ref long
lpFrequency);
}

回答2:

如果我没记错的话,在System.Thread命名空间下的有一个定时器类,类名叫Timer(注意不要和另一个命名空间下的Timer混淆),里面可以设置毫秒级定时操作。你可以找相关的帮助看看。

在很多.net开始的企业级应用windows服务中,常用到这个类做定时任务。

回答3:

使用StopWatch类
不用native API