-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSessionPinger.cs
98 lines (84 loc) · 1.9 KB
/
SessionPinger.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
using System;
using System.Threading;
namespace MowChat
{
public class SessionPinger : IDisposable
{
/// <summary>
/// Instance of the session pinger.
/// </summary>
private static SessionPinger _instance;
/// <summary>
/// Start the session pinger, if it's not running yet.
/// </summary>
public static void StartPinging()
{
if (_instance != null) return;
_instance = new SessionPinger();
}
/// <summary>
/// Stop the session pinger, if it's running.
/// </summary>
public static void StopPinging()
{
if (_instance == null) return;
_instance.Dispose();
_instance = null;
}
/// <summary>
/// The thread that's pinging to keep the session alive.
/// </summary>
private readonly Thread _thread;
/// <summary>
/// Used for locking to be able to abort the thread safely.
/// </summary>
private readonly object _padlock = new object();
/// <summary>
/// Whether we should stop pinging.
/// </summary>
private bool _continuePinging = true;
/// <summary>
/// Constructor.
/// </summary>
private SessionPinger()
{
_thread = new Thread(TimedPing);
_thread.Start();
}
/// <summary>
/// Dispose of the thread.
/// </summary>
public void Dispose()
{
if (_thread == null || !_thread.IsAlive) return;
_continuePinging = false;
lock (_padlock)
{
Monitor.Pulse(_padlock);
}
}
/// <summary>
/// Every 10 minutes, until we should stop, ping the API to keep the session alive.
/// </summary>
private void TimedPing()
{
while (_continuePinging)
{
// Wait 10 minutes or until the padlock is cancelled.
lock (_padlock)
{
Monitor.Wait(_padlock, TimeSpan.FromMinutes(10));
}
if (_continuePinging)
Ping();
}
}
/// <summary>
/// Ping the API to keep the session alive.
/// </summary>
private static void Ping()
{
API.Instance.Post<object>(null, "auth/ping");
}
}
}