-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathProgramShutdownTokenSource.cs
58 lines (51 loc) · 1.5 KB
/
ProgramShutdownTokenSource.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
using System;
using System.Threading;
namespace Tgstation.Server.Host.System
{
/// <summary>
/// Contains a <see cref="CancellationToken"/> that triggers when the operating system requests the program shuts down.
/// </summary>
sealed class ProgramShutdownTokenSource : IDisposable
{
/// <summary>
/// Lock <see cref="object"/> for <see cref="cancellationTokenSource"/>.
/// </summary>
readonly object tokenSourceAccessLock;
/// <summary>
/// The <see cref="CancellationTokenSource"/> for the <see cref="ProgramShutdownTokenSource"/>.
/// </summary>
CancellationTokenSource cancellationTokenSource;
/// <summary>
/// Gets the <see cref="CancellationToken"/>.
/// </summary>
public CancellationToken Token => cancellationTokenSource?.Token ?? default;
/// <summary>
/// Initializes a new instance of the <see cref="ProgramShutdownTokenSource"/> class.
/// </summary>
public ProgramShutdownTokenSource()
{
tokenSourceAccessLock = new object();
cancellationTokenSource = new CancellationTokenSource();
AppDomain.CurrentDomain.ProcessExit += (sender, args) =>
{
lock (tokenSourceAccessLock)
cancellationTokenSource?.Cancel();
};
Console.CancelKeyPress += (sender, args) =>
{
args.Cancel = true;
lock (tokenSourceAccessLock)
cancellationTokenSource?.Cancel();
};
}
/// <inheritdoc />
public void Dispose()
{
lock (tokenSourceAccessLock)
{
cancellationTokenSource?.Dispose();
cancellationTokenSource = null;
}
}
}
}