-
Notifications
You must be signed in to change notification settings - Fork 1
/
TimeoutNet.cs
59 lines (50 loc) · 1.81 KB
/
TimeoutNet.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
using System.Collections.Concurrent;
namespace Timeout.Net
{
public class TimeoutContext<TKey, TValue>
{
private readonly ConcurrentDictionary<TKey, Tuple<TValue, Task>> _dictionary = new ConcurrentDictionary<TKey, Tuple<TValue, Task>>();
public delegate void KeyChange(TKey key);
public event KeyChange OnScheduledItemExpired;
public event KeyChange OnItemScheduled;
public TimeoutNet()
{
this.OnScheduledItemExpired += TimeOutStatics.DefaultScheduledExpired;
}
public void SetTimeout(TKey key, TValue value, TimeSpan timeSpan)
{
Task timeoutTask = Task.Delay(timeSpan).ContinueWith(t =>
{
lock (_dictionary)
{
if (_dictionary.TryRemove(key, out _))
{
if (OnScheduledItemExpired != null)
OnScheduledItemExpired(key);
}
}
});
_dictionary.AddOrUpdate(key, Tuple.Create(value, timeoutTask), (k, v) => Tuple.Create(value, timeoutTask));
if (OnItemScheduled != null)
OnItemScheduled(key);
}
public bool GetValue(TKey key, out TValue value)
{
if (_dictionary.TryGetValue(key, out var tuple))
{
value = tuple.Item1;
return true;
}
value = default;
return false;
}
}
public static class TimeOutStatics
{
// By default, this method is assigned to delegate "OnScheduledItemExpired" when the class is created
public static void DefaultScheduledExpired(Action key)
{
key();
}
}
}