首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C# 中定时器的有关问题

2012-04-10 
C# 中定时器的问题各位大侠,请问C#中有没有一个类似定时器的函数,我需要每20毫秒发送一个数据,不是Timer控

C# 中定时器的问题
各位大侠,请问C#中有没有一个类似定时器的函数,我需要每20毫秒发送一个数据,不是Timer控件,比它精确的函数,最好能知道它的精确度,谢谢各位的帮助啊

[解决办法]

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

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

你要纳秒级别的话:
[timer ]是不行的,[stopwatcher ]+while 也不行,只会耗尽CPU ,
只有用 汇编 写的定时器才能达到你的要求。
[解决办法]
windows不是实时系统,在应用层不可能做到比timer更准。
stopwatcher可以读到更精确的时间,但就算你把线程设成高优先级用pulling的办法也没办法保证20毫秒发一个数据。
驱动层可能可以做到。
[解决办法]
System.Threading.Timer 定时器,非UI Timer,定时器中的优选者。
可精确控制,启动,次数,间隔
[解决办法]

C# code
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();        }    }} 

热点排行