当许多任务正在运行时,计时器被延迟

本文关键字:计时器 延迟 运行时 多任务 | 更新日期: 2023-09-27 18:18:25

我使用计时器来计算动作进度,但如果有许多正在运行的任务,计时器会延迟。

下面是我的定时器类:

public class TimingAction
{
    private const int ProgressUpdateIntervalDefault = 500;
    public int Duration { get; set; }
    public int ProgressUpdateInterval { get; set; }
    public event Action<double> ProgressUpdated;
    private readonly Timer progressTimer = new Timer();
    private readonly Timer scanTimer = new Timer();
    private readonly Stopwatch timeWatch = new Stopwatch();
    public TimingAction()
    {
        ProgressUpdateInterval = ProgressUpdateIntervalDefault;
    }
    public void Start()
    {
        // Stop progress after duration time
        timeWatch.Restart();
        scanTimer.Interval = Duration;
        scanTimer.Elapsed += (o, e) => Stop();
        // Send progress notification
        progressTimer.Interval = ProgressUpdateInterval;
        progressTimer.Elapsed += (o, e) =>
        {
            if (ProgressUpdated != null)
            {
                ProgressUpdated((double)timeWatch.ElapsedMilliseconds / Duration);
            }
        };
        timeWatch.Start();
        scanTimer.Start();
        progressTimer.Start();
    }
    public void Stop()
    {
        scanTimer.Stop();
        progressTimer.Stop();
        timeWatch.Stop();
    }
}

下面是测试类:

class Program
{
    static void Main(string[] args)
    {
        int wt, ct;
        ThreadPool.GetAvailableThreads(out wt, out ct);
        Console.WriteLine("Before starting tasks : worker thread {0}, completion thread {1}", wt, ct);
        for (int i = 0; i < 5; i++)
        {
            int taskID = i;
            //Task.Factory.StartNew(() => TestTask(taskID));   
            var t = new Thread(() => TestTask(taskID));
            t.Start();
        }
        ThreadPool.GetAvailableThreads(out wt, out ct);
        Console.WriteLine("After starting tasks : worker thread {0}, completion thread {1}", wt, ct);
        var action = new TimingAction();
        action.ProgressUpdated += action_ProgressUpdated;
        action.ProgressUpdateInterval = 100;
        action.Duration = 1000;
        action.Start();
        Console.WriteLine("After starting timer : worker thread {0}, completion thread {1}", wt, ct);
        Console.ReadLine();
    }
    static void action_ProgressUpdated(double obj)
    {
        Console.WriteLine("progress {0:00}%", obj*100);
    }
    static void TestTask(int taskID)
    {
        while (true)
        {
            Thread.Sleep(1000);
            //Console.WriteLine("Thread ID: {0}, Task {1}", Thread.CurrentThread.ManagedThreadId, taskID);
        }
    }
}

当我使用Thread类运行TestTask方法时,进度工作良好,结果是:

Before starting tasks : worker thread 1023, completion thread 1000
After starting tasks : worker thread 1023, completion thread 1000
After starting timer : worker thread 1023, completion thread 1000
progress 16%
progress 21%
progress 33%
progress 44%
progress 54%
progress 65%
progress 76%
progress 87%
progress 98%

但是当我使用Task类运行TestTask方法时,计时器Elapsed调用被延迟,结果是:

Before starting tasks : worker thread 1023, completion thread 1000
After starting tasks : worker thread 1019, completion thread 1000
After starting timer : worker thread 1019, completion thread 1000
progress 105%
progress 199%

延误的原因是什么?如何解决?但是,延迟只发生在开始的2秒,如果我将持续时间增加到10秒,那么在延迟2s后进度就会正常运行。

应用程序在。net Framework 4.5下运行

当许多任务正在运行时,计时器被延迟

我不能确定你使用的是哪种类型的定时器,因为我们看不到顶部的using语句…但是我假设它是System.Windows.Forms.Timer。

这篇微软的文章解释了计时器之间的区别。如果您对何时触发计时器有严格的要求,那么在这里使用System.Timers.Timer可能是更好的选择。