C# 仅在延迟时间后执行方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15185647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:22:45  来源:igfitidea点击:

Execute a method after delay on time only

c#.netwpfwindows-phone-7windows-phone

提问by MTA

I'm using this method to call another method every 60 seconds:

我正在使用此方法每 60 秒调用一次另一个方法:

Timer updateTimer = new Timer(testt, null, 
                              new TimeSpan(0, 0, 0, 0, 1), new TimeSpan(0, 0, 60));

It is possible to call this method only once after delay of 1 millisecond?

是否可以在延迟 1 毫秒后仅调用一次此方法?

采纳答案by Jon Skeet

Assuming this is a System.Threading.Timer, from the documentation for the constructor's final parameter:

假设这是一个System.Threading.Timer, 来自构造函数的最终参数的文档:

period
The time interval between invocations of the methods referenced by callback. Specify negative one (-1) milliseconds to disable periodic signaling.

period
回调引用的方法调用之间的时间间隔。指定负一 (-1) 毫秒以禁用定期信号。

So:

所以:

Timer updateTimer = new Timer(testt, null,
                              TimeSpan.FromMilliseconds(1),   // Delay by 1ms
                              TimeSpan.FromMilliseconds(-1)); // Never repeat

Is a delay of 1ms really useful though? Why not just execute it immediately? If you're really just trying to execute it on a thread-pool thread, there are better ways of achieving that.

1ms 的延迟真的有用吗?为什么不立即执行呢?如果你真的只是想在线程池线程上执行它,那么有更好的方法来实现这一点。

回答by syedmoulaali

System.Timers.Timer aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 60 seconds (60000 milliseconds).
aTimer.Interval = 60000;
//for enabling for disabling the timer.
aTimer.Enabled = true;
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
     //disable the timer
    aTimer.Enabled = false;
    Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
 }