如果先前的调用尚未完成,则不会运行的.net计时器

时间:2014-09-25 18:20:52

标签: c# .net timer

我有一个程序需要每60秒做一次。几乎总是这需要1-2秒才能完成,但有一个条件可能需要几分钟。

如果之前的调用尚未完成,是否有人知道.net计时器不会调用“time elapsed”方法?

我显然可以通过这样的支票来做到这一点......

如果(beingRun){

}

3 个答案:

答案 0 :(得分:0)

您可以编写async方法来执行此操作:

public async void Recur(Action action, TimeSpan time, CancellationToken token)
{
    while(!token.IsCancellationRequested)
    {
        action();
        try
        {
            await Task.Delay(time, token);
        }
        catch(TaskCancelledException)
        {
            break;
        }
    }
}

并使用它:

CancellationTokenSource cts = new CancellationTokenSource();
Recur(() => DoMyBigJob(), TimeSpan.FromMinutes(1), cts.Token);

并杀死它

cts.Token.Cancel();

不要丢失您的CancellationTokenSource,否则您将拥有一个无法控制的流氓异步循环。

答案 1 :(得分:0)

我通常只是存储计时器是否应该以bool处理,如下所示:

Timer timer = new Timer();
timer.Elapsed += timer_Elapsed;
timer.Interval = TimeSpan.FromSeconds(60).TotalMiliseconds;

bool processingSomething = false;

void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    if (!processingSomething)
    {
        processingSomething = true;

        // Process stuff here . . .

        processingSomething = false;
    }
}

答案 2 :(得分:0)

使用Enabled属性。

using System;
using System.Linq;
using System.Text;
using System.Timers;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static readonly Timer MyTimer = new Timer()
        {
            Interval = 60,
        };

        private static void Main(string[] args)
        {
            MyTimer.Elapsed += MyTimerOnElapsed;
        }

        private static void MyTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            MyTimer.Enabled = false;

            try
            {
                // Some code here
            }
            finally
            {
                MyTimer.Enabled = true;
            }
        }
    }
}
相关问题