using System.Threading; namespace Bro.Common.Helper { public delegate void OnTimeoutDelegate(); public class TimeOutHelper { private const int TIMEINTERVAL = 1000; private bool isPause = false; int timeTick = 0; public event OnTimeoutDelegate OnTimeout; public Timer MonitorTimer { get; set; } /// /// 超时最大时间,以秒为单位 /// public int MaxLimit { get; set; } = 250; public TimeOutHelper() { InitialTimer(); } private void InitialTimer() { MonitorTimer = new Timer(new TimerCallback(OnTimeTick), null, Timeout.Infinite, TIMEINTERVAL); } private void OnTimeTick(object state) { if (!isPause) { timeTick++; } if (timeTick >= MaxLimit) { OnTimeout?.Invoke(); Stop(); } } public TimeOutHelper(int limit) { MaxLimit = limit; InitialTimer(); } public void Start() { timeTick = 0; MonitorTimer.Change(0, TIMEINTERVAL); } public void Pause() { isPause = true; } public void Resume() { isPause = false; } public void Stop() { MonitorTimer.Change(Timeout.Infinite, Timeout.Infinite); } } }