简体   繁体   English

C#Timer.Change方法

[英]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 我需要创建一个每5秒运行一次的函数,无论结果如何,我都会通过MSDN库找到这个http://msdn.microsoft.com/en-us/library/yz1c7148.aspx ,我认为这是我需要的,但我需要了解更多关于到期时间和周期参数的信息

For my understanding:- DueTime is it the time that will wait before start the timer ? 根据我的理解: - DueTime是在启动计时器之前等待的时间吗? Periodtime is it time that repeat the time ? 时间段是重复时间的时间吗?

my question is whether my understanding is correct regarding the Timer provide by msdn. 我的问题是我对msdn提供的Timer提供的理解是否正确。 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 ? 此外,如果我想设置我的时间每5秒运行一次,无论之前的计时器是否完成,或者我应该设置它?

只需创建一个虚拟计时器,每五秒钟打一次,然后使用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. 但是我应该提一下System.Threading.Timer不是很准确,每次调用都会有一些累积错误。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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