Answer the question
In order to leave comments, you need to log in
How to make a timer to do a long job?
There is a code.
// Создаем таймер из System.Threading
Timer timer = new Timer(OnTimer, state: null, dueTime: 0, period: 1000);
static void OnTimer(object state)
{
Thread.Sleep(5000); // Симуляция работы
}
// Создаем таймер
timer = new System.Timers.Timer(1000);
timer.Elapsed += Timer_Elapsed;
timer.Start();
private static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
timer.Stop(); // Останавливаем таймер чтобы он не вызвался второй раз через секунду.
Thread.Sleep(5000); // Симуляция работы
timer.Start();
}
Answer the question
In order to leave comments, you need to log in
I use this solution, the timer waits until the work is finished. In fact, I just turn it off while the job is running, and after completion or exception, I start it again.
public class TestWorker
{
private readonly Timer _timer;
public TestWorker()
{
_timer = new Timer(
Callback,
null,
TimeSpan.FromSeconds(1),
TimeSpan.Zero);
}
private void Callback(object state)
{
try
{
//work imitation
Thread.Sleep(5000);
}
finally
{
_timer.Change(
TimeSpan.FromSeconds(1),
TimeSpan.Zero);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question