Создать таймер в потоке - C#

Узнай цену своей работы

Формулировка задачи:

У меня есть событие, оно вызывается безусловно в конце очереди других событий. Проблема в том, что мне нужно чтобы событие вызывалось один раз в конце всех очередей. Хочу добавить нечто вроде таймера в отдельном потоке, чтобы при обращении к нему из другого потока до истечения времени таймер начинал отсчёт заново, а по истечению времени событие выполнялось. Однако не совсем понимаю как подобное организовать. Заранее спасибо.

Решение задачи: «Создать таймер в потоке»

textual
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7.  
  8. namespace Bill77
  9. {
  10.     public class WatchDog : IDisposable
  11.     {
  12.         public WatchDog(TimeSpan timeoutInterval)
  13.         {
  14.             this.TimeOutInterval = timeoutInterval;
  15.             this.mMonitorTask = null;
  16.             this.mCancellationToken = null;
  17.             this.mSignalEvent = new ManualResetEventSlim();
  18.  
  19.             this.Start();
  20.         }
  21.  
  22.         public void Dispose()
  23.         {
  24.             this.Stop();
  25.         }
  26.  
  27.         public TimeSpan TimeOutInterval { get; set; }
  28.         public event EventHandler TimeIsOut;
  29.         public event EventHandler<RemaningTimeChangedEventArgs> TimeChanged;
  30.  
  31.         private Task mMonitorTask;
  32.         private CancellationTokenSource mCancellationToken;
  33.         private ManualResetEventSlim mSignalEvent;
  34.  
  35.         private void Start()
  36.         {
  37.             this.mCancellationToken = new CancellationTokenSource();
  38.             this.mMonitorTask = Task.Factory.StartNew(this.Monitor, this.mCancellationToken.Token, this.mCancellationToken.Token);
  39.         }
  40.  
  41.         private void Stop()
  42.         {
  43.             if (this.mCancellationToken != null)
  44.             {
  45.                 try
  46.                 {
  47.                     this.mCancellationToken.Cancel();
  48.                     this.mMonitorTask.Wait();
  49.                 }
  50.                 catch (AggregateException exc)
  51.                 {
  52.                     if (this.mMonitorTask.IsCanceled)
  53.                     {
  54.                     }
  55.                 }
  56.                 catch (Exception exc)
  57.                 {
  58.                 }
  59.                 finally
  60.                 {
  61.                     this.mCancellationToken.Dispose();
  62.                     this.mMonitorTask.Dispose();
  63.                 }
  64.             }
  65.         }
  66.  
  67.         public void Signal()
  68.         {
  69.             this.mSignalEvent.Set();
  70.         }
  71.  
  72.         private void Monitor(object ct)
  73.         {
  74.             CancellationToken token = (CancellationToken)ct;
  75.             DateTime? lastSignalTime = null;
  76.  
  77.             while (true)
  78.             {
  79.                 token.ThrowIfCancellationRequested();
  80.  
  81.                 if (this.mSignalEvent.Wait(100, token))
  82.                 {
  83.                     this.mSignalEvent.Reset();
  84.                     lastSignalTime = DateTime.Now;
  85.                 }
  86.  
  87.                 if (lastSignalTime.HasValue)
  88.                 {
  89.                     if (lastSignalTime.Value.Add(this.TimeOutInterval) < DateTime.Now)
  90.                     {
  91.                         this.TimeIsOut?.Invoke(this, EventArgs.Empty);
  92.                         lastSignalTime = null;
  93.                     }
  94.                     else
  95.                     {
  96.                         TimeSpan remaining = lastSignalTime.Value.Add(this.TimeOutInterval).Subtract(DateTime.Now);
  97.                         this.TimeChanged?.Invoke(this, new RemaningTimeChangedEventArgs(remaining));
  98.                     }
  99.                 }
  100.             }
  101.         }
  102.  
  103.         public class RemaningTimeChangedEventArgs : EventArgs
  104.         {
  105.             public RemaningTimeChangedEventArgs(TimeSpan remainingTime)
  106.             {
  107.                 this.RemainingTime = remainingTime;
  108.             }
  109.  
  110.             public TimeSpan RemainingTime { get; private set; }
  111.         }
  112.     }
  113. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

6   голосов , оценка 3.833 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы