仅在延迟时间后执行方法

时间:2022-10-26 01:17:33

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毫秒后,可以只调用一次这种方法吗?

2 个解决方案

#1


18  

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.

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

#2


3  

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);
 }

#1


18  

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.

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

#2


3  

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);
 }