C# Timer.Change Method

落花浮王杯 提交于 2019-12-13 03:59:05

问题


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 ?


回答1:


just create a dummy timer to tick every five seconds and then launch your function in Tick event using BeginInvoke.




回答2:


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


来源:https://stackoverflow.com/questions/19316514/c-sharp-timer-change-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!