C# 中定时器的问题

wl04071167 2012-04-03 10:59:44
各位大侠,请问C#中有没有一个类似定时器的函数,我需要每20毫秒发送一个数据,不是Timer控件,比它精确的函数,最好能知道它的精确度,谢谢各位的帮助啊
...全文
655 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
FounderSG 2012-04-03
  • 打赏
  • 举报
回复
windows不是实时系统,在应用层不可能做到比timer更准。
stopwatcher可以读到更精确的时间,但就算你把线程设成高优先级用pulling的办法也没办法保证20毫秒发一个数据。
驱动层可能可以做到。
hetengfei_ 2012-04-03
  • 打赏
  • 举报
回复

用timer 不行吗,试试改改它的优先级,也可以 stopwatcher 来看看你的timer 每次触发的时间精度,

stopwatcher timer 都是毫秒级别的,
当然机器周期是纳秒级别的。

你要纳秒级别的话

timer 是不行的,stopwatcher +while 也不行,只会耗尽CPU ,
只有用 汇编 写的定时器才能达到你的要求。
mingcsharp 2012-04-03
  • 打赏
  • 举报
回复
stopwatcher你看看是不是你想要的
色拉油 2012-04-03
  • 打赏
  • 举报
回复
Timer也能控制啊,interval设成20
至于你说的精确度,应该是你程序运行时间可网络延迟时间决定的吧
orochiheart 2012-04-03
  • 打赏
  • 举报
回复
控件是一种 代码有两种
http://www.360doc.com/content/12/0218/17/8791989_187629561.shtml
蔡袅 2012-04-03
  • 打赏
  • 举报
回复
using System;
using System.Threading;

class TimerExample
{
static void Main()
{
AutoResetEvent autoEvent = new AutoResetEvent(false);
StatusChecker statusChecker = new StatusChecker(10);

// Create the delegate that invokes methods for the timer.
TimerCallback timerDelegate =
new TimerCallback(statusChecker.CheckStatus);

TimeSpan delayTime = new TimeSpan(0, 0, 1);
TimeSpan intervalTime = new TimeSpan(0, 0, 0, 0, 250);

// Create a timer that signals the delegate to invoke
// CheckStatus after one second, and every 1/4 second
// thereafter.
Console.WriteLine("{0} Creating timer.\n",
DateTime.Now.ToString("h:mm:ss.fff"));
Timer stateTimer = new Timer(
timerDelegate, autoEvent, delayTime, intervalTime);

// When autoEvent signals, change the period to every
// 1/2 second.
autoEvent.WaitOne(5000, false);
stateTimer.Change(new TimeSpan(0),
intervalTime + intervalTime);
Console.WriteLine("\nChanging period.\n");

// When autoEvent signals the second time, dispose of
// the timer.
autoEvent.WaitOne(5000, false);
stateTimer.Dispose();
Console.WriteLine("\nDestroying timer.");
}
}

class StatusChecker
{
int invokeCount, maxCount;

public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}

// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString());

if(invokeCount == maxCount)
{
// Reset the counter and signal Main.
invokeCount = 0;
autoEvent.Set();
}
}
}
蔡袅 2012-04-03
  • 打赏
  • 举报
回复
System.Threading.Timer 定时器,非UI Timer,定时器中的优选者。
可精确控制,启动,次数,间隔

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧