-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTimer.cs
139 lines (115 loc) · 2.31 KB
/
Timer.cs
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
using System;
using System.Drawing;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using SDL2;
using static SDL2.SDL;
namespace SDLWrapper
{
public class Timer : IDisposable
{
private uint _interval;
SDL_TimerCallback _callback;
GCHandle _gcHandle;
public delegate void TickEventHandler(object sender, TimerEventArgs e);
public event TickEventHandler Tick;
public Timer(uint interval)
{
Initializers.InitializeTimer();
_interval = interval;
_callback = new SDL_TimerCallback(TickCallback);
_gcHandle = GCHandle.Alloc(_callback);
if (_interval > 0)
{
Handle = new IntPtr(
SDL_AddTimer(interval, _callback, IntPtr.Zero));
if (Handle == IntPtr.Zero)
{
throw new SDLException();
}
}
}
public IntPtr Handle
{
get;
private set;
}
public uint Interval
{
get
{
return _interval;
}
set
{
if (value != _interval)
{
if (Handle != IntPtr.Zero)
{
SDL_RemoveTimer(Handle.ToInt32());
Handle = IntPtr.Zero;
}
if (value > 0)
{
Handle = new IntPtr(
SDL_AddTimer(value, _callback, IntPtr.Zero));
if (Handle == IntPtr.Zero)
{
throw new SDLException();
}
}
}
}
}
protected virtual void OnTick(TimerEventArgs e)
{
Tick?.Invoke(this, e);
}
private uint TickCallback(uint interval, IntPtr param)
{
TimerEventArgs e = new TimerEventArgs();
e.Interval = Interval;
OnTick(e);
return (_interval = e.Interval);
}
public static implicit operator IntPtr(Timer timer)
{
return timer.Handle;
}
public static implicit operator bool(Timer timer)
{
return (timer != null && timer.Handle != IntPtr.Zero);
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (Handle != IntPtr.Zero)
{
SDL_RemoveTimer(Handle.ToInt32());
Handle = IntPtr.Zero;
}
if (_callback != null)
{
_gcHandle.Free();
_callback = null;
}
disposedValue = true;
}
}
~Timer()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}