-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseThreadSafeConnectionHandler.cs
More file actions
95 lines (77 loc) · 2.77 KB
/
Copy pathBaseThreadSafeConnectionHandler.cs
File metadata and controls
95 lines (77 loc) · 2.77 KB
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
using Aragas.TupleEventSystem;
using System;
using System.Threading;
namespace Aragas.QServer.Core
{
public abstract class BaseThreadSafeConnectionHandler
{
public BaseEventHandler<EventArgs> Ready { get; set; } = new WeakReferenceEventHandler<EventArgs>();
public BaseEventHandler<EventArgs> Disconnected { get; set; } = new WeakReferenceEventHandler<EventArgs>();
//public event EventHandler Ready;
//public event EventHandler Disconnected;
protected CancellationTokenSource UpdateToken { get; set; } = new CancellationTokenSource();
protected ManualResetEventSlim UpdateLock { get; } = new ManualResetEventSlim(false);
protected ManualResetEventSlim ConnectionLock { get; } = new ManualResetEventSlim(true); // Will cause deadlock if false. See Leave();
private bool IsDisposing { get; set; }
public void StartListening()
{
if (!UpdateLock.IsSet)
{
//UpdateToken = new CancellationTokenSource();
new Thread(Update).Start();
}
else
{
throw new Exception("UpdateThread is already running!");
}
}
protected void Join()
{
Ready?.Invoke(this, EventArgs.Empty);
}
protected void Leave()
{
ConnectionLock.Wait(); // this should ensure we will send every packet enqueued at the moment of calling Leave()
if (UpdateToken?.IsCancellationRequested == false)
{
UpdateToken.Cancel();
UpdateLock.Wait(); // Wait for the Update cycle to finish
}
Disconnected?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Will raise Disconnected event.
/// </summary>
/// <param name="reason"></param>
public virtual void SendKick(string reason = "") { Leave(); }
public abstract void Update();
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!IsDisposing)
{
if (disposing)
{
if (UpdateToken?.IsCancellationRequested == false)
{
UpdateToken.Cancel();
UpdateLock.Wait();
}
UpdateLock.Dispose();
ConnectionLock.Dispose();
Ready?.Dispose();
Disconnected?.Dispose();
}
IsDisposing = true;
}
}
~BaseThreadSafeConnectionHandler()
{
Dispose(false);
}
}
}