aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Core/Threading/ActionTimer.cs
blob: eda115047c1dba1069b84759e0c5268c82024406 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace Tango.Core.Threading
{
    /// <summary>
    /// Represents an action executer with a predefined interval and a reset mechanism.
    /// </summary>
    public class ActionTimer : IDisposable
    {
        private Timer _timer;
        private Action _action;

        /// <summary>
        /// Initializes a new instance of the <see cref="ActionTimer"/> class.
        /// </summary>
        /// <param name="interval">The interval.</param>
        public ActionTimer(TimeSpan interval)
        {
            _timer = new Timer(interval.TotalMilliseconds);
            _timer.Enabled = true;
            _timer.Stop();
            _timer.Elapsed += _timer_Elapsed;
        }

        /// <summary>
        /// Resets the current timer and replaces the action to be invoked.
        /// </summary>
        /// <param name="action">The action.</param>
        public void ResetReplace(Action action)
        {
            if (_timer != null)
            {
                _timer.Stop();
                _action = action;
                _timer.Start();
            }
        }

        private void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _timer.Stop();
            _action?.Invoke();
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            if (_timer != null)
            {
                _timer.Stop();
                _timer = null;
            }
        }
    }
}