我正在使用Timer来计算操作进度,但如果有许多正在运行的任务,则计时器会延迟。
以下是我的计时器课程:
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秒,则在2秒延迟后进展顺利。
该应用程序在.Net Framework 4.5下运行。
答案 0 :(得分:0)
我无法确定您正在使用哪种类型的Timer,因为我们无法在顶部看到using语句...但我将假设它是System.Windows.Forms.Timer
This Microsoft article解释了计时器之间的差异。如果你对定时器被触发的时间有严格的要求,那么在这里使用System.Timers.Timer可能是更好的选择。