Skip to content

Commit 6191c5e

Browse files
Temp.cs
1 parent bb7f9dd commit 6191c5e

File tree

1 file changed

+118
-0
lines changed

1 file changed

+118
-0
lines changed

Temp.cs

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
using System;
2+
using System.Collections.Concurrent;
3+
using System.Diagnostics;
4+
using System.Threading;
5+
using System.Threading.Tasks;
6+
7+
namespace ExpressionTree
8+
{
9+
public class Timer
10+
{
11+
static readonly ConcurrentDictionary<TimerInstance, string> activeTimers = new ConcurrentDictionary<TimerInstance, string>();
12+
static readonly ConcurrentBag<TimerInstance> timerPool = new ConcurrentBag<TimerInstance>();
13+
14+
static readonly AutoResetEvent a = new AutoResetEvent(false);
15+
static int Number = 0;
16+
static Timer()
17+
{
18+
TimerInstance.rec = activeTimers;
19+
StartTimerThread();
20+
}
21+
22+
private static void StartTimerThread()
23+
{
24+
Thread t = new Thread(() =>
25+
{
26+
SpinWait sw = new SpinWait();
27+
Stopwatch stopwatch = new Stopwatch();
28+
while (true)
29+
{
30+
a.WaitOne();
31+
stopwatch.Restart();
32+
Thread.Sleep(10);
33+
//sw.SpinOnce();
34+
//stopwatch.Stop();
35+
36+
Tick(stopwatch);
37+
}
38+
});
39+
40+
// t.Start();
41+
Looper();
42+
43+
}
44+
private async static void Looper()
45+
{
46+
Stopwatch stopwatch = new Stopwatch();
47+
while (true)
48+
{
49+
50+
stopwatch.Restart();
51+
await Task.Delay(10).ConfigureAwait(false);
52+
Tick(stopwatch);
53+
}
54+
}
55+
56+
private static void Tick(Stopwatch sw)
57+
{
58+
if(activeTimers.Count == 0)
59+
return;
60+
61+
a.Set();
62+
foreach (var item in activeTimers)
63+
{
64+
item.Key.Tick((int)sw.ElapsedMilliseconds);
65+
}
66+
}
67+
68+
private static TimerInstance GetTimer()
69+
{
70+
var timer = new TimerInstance();
71+
timer.number = Interlocked.Increment(ref Number);
72+
return timer;
73+
}
74+
75+
public static void Wait(int miliseconds,Action OnCompleted)
76+
{
77+
var timer = GetTimer();
78+
timer.remaining = miliseconds;
79+
timer.Completed += OnCompleted;
80+
activeTimers.TryAdd(timer, null);
81+
a.Set();
82+
}
83+
84+
class TimerInstance
85+
{
86+
public int remaining;
87+
public Action Completed;
88+
public static ConcurrentDictionary<TimerInstance, string> rec;
89+
public static ConcurrentBag<TimerInstance> timerPool;
90+
public int number;
91+
public void Tick(int dt)
92+
{
93+
remaining -= dt;
94+
if (remaining <= 0)
95+
{
96+
Complete();
97+
}
98+
}
99+
100+
private void Complete()
101+
{
102+
rec.TryRemove(this, out _);
103+
Completed?.Invoke();
104+
Reset();
105+
}
106+
107+
public void Reset()
108+
{
109+
//remaining = 1000;
110+
Completed = null;
111+
}
112+
public override int GetHashCode()
113+
{
114+
return number;
115+
}
116+
}
117+
}
118+
}

0 commit comments

Comments
 (0)