-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
60 lines (51 loc) · 1.94 KB
/
Program.cs
File metadata and controls
60 lines (51 loc) · 1.94 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
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace DockerWindowsSignalRepro
{
class Program
{
static Task Main(string[] args) => new Program().RunAsync();
public Program()
{
_cts = new CancellationTokenSource();
if (!SetConsoleCtrlHandler(ConsoleCtrlHandler, add: true))
throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
}
public async Task RunAsync()
{
while (true)
{
Console.WriteLine($"Running at: {DateTimeOffset.Now}");
await Task.Delay(1000, _cts.Token);
}
}
private readonly CancellationTokenSource _cts;
private bool ConsoleCtrlHandler(ConsoleControlEvent controlType)
{
if (controlType == ConsoleControlEvent.CTRL_C_EVENT ||
controlType == ConsoleControlEvent.CTRL_CLOSE_EVENT ||
controlType == ConsoleControlEvent.CTRL_SHUTDOWN_EVENT)
{
Console.WriteLine($"Received event: {controlType}");
Task.Run(() => _cts.Cancel());
return true;
}
return false;
}
private enum ConsoleControlEvent : uint
{
CTRL_C_EVENT = 0,
CTRL_CLOSE_EVENT = 2,
CTRL_SHUTDOWN_EVENT = 6,
}
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private delegate bool SetConsoleCtrlHandlerHandlerRoutine(ConsoleControlEvent controlType);
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetConsoleCtrlHandler(SetConsoleCtrlHandlerHandlerRoutine handler,
[MarshalAs(UnmanagedType.Bool)] bool add);
}
}