简体   繁体   中英

C# Timer.Change Method

I am required to create a function that will run every 5 second no matter what is the outcome , I go through the MSDN library and found out this http://msdn.microsoft.com/en-us/library/yz1c7148.aspx , I think this is what I need , but I need to know more about the due time and period parameters

For my understanding:- DueTime is it the time that will wait before start the timer ? Periodtime is it time that repeat the time ?

my question is whether my understanding is correct regarding the Timer provide by msdn. besides , if I want to set my time runn every 5 second no matter the previous timer is complete or not what should I set it ?

只需创建一个虚拟计时器,每五秒钟打一次,然后使用BeginInvokeTick事件中启动您的函数。

You are absolutely correct in your understanding. The following code should do what you want:

System.Threading.Timer timer = new System.Threading.Timer(Callback, null, 0, 5 * 1000);

however I should mention what System.Threading.Timer is not quite accurate and there will be some accumulating error on each call. For example the following code

static void Main(string[] args)
{
    System.Threading.Timer timer = new System.Threading.Timer(Callback, null, 0, 1 * 1000);
    Console.ReadLine();
}

static void Callback(object state)
{
    Console.WriteLine(DateTime.Now.ToString("hh:MM:ss:ffff"));
}

produces the following result on my computer:

03:10:14:8014
03:10:15:8154
03:10:16:8294
03:10:17:8434
03:10:18:8574
03:10:19:8714
03:10:20:8854
03:10:21:8994
03:10:22:9134
03:10:23:9274
03:10:24:9414
03:10:25:9554
03:10:26:9694
03:10:27:9834
03:10:28:9974
03:10:30:0114
03:10:31:0254

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM