Пример #1
0
        private void TimerCallback(object state)
        {
            CancellationTokenSource cts;

            lock (_locker)
            {
                // Timer will not cancel the work item queued before the timer is stopped.
                // We don't want to handle the callback after a timer is stopped.
                if (!Enabled)
                {
                    return;
                }

                cts = _cts;
            }

            try
            {
                // in try block because "cts.Token" can throw ObjectDisposedException
                Elapsed.Raise(this, cts.Token);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            lock (_locker)
            {
                if (cts.IsCancellationRequested)
                {
                    cts.Dispose();
                }
                if (!Enabled)
                {
                    return;
                }

                if (AutoResetMode == TimerAutoResetMode.Relative)
                {
                    _timer.Change(Interval, Timeout.InfiniteTimeSpan);
                }
            }
        }