Repository navigation
Expand file tree
/
Copy pathSingleInstanceManager.cs
More file actions
64 lines (55 loc) · 1.56 KB
/
Copy pathSingleInstanceManager.cs
File metadata and controls
64 lines (55 loc) · 1.56 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
namespace Rounder.Windows;
public sealed class SingleInstanceManager : IDisposable
{
private const string MutexName = @"Local\Rounder.Windows.Singleton";
private const string ActivationEventName = @"Local\Rounder.Windows.Activate";
private readonly Mutex mutex;
private readonly EventWaitHandle activationEvent;
private RegisteredWaitHandle? registeredWait;
public SingleInstanceManager()
{
mutex = new Mutex(initiallyOwned: true, MutexName, out var createdNew);
IsFirstInstance = createdNew;
activationEvent = new EventWaitHandle(false, EventResetMode.AutoReset, ActivationEventName);
}
public bool IsFirstInstance { get; }
public void StartListening(Action activationRequested)
{
if (!IsFirstInstance)
{
return;
}
registeredWait = ThreadPool.RegisterWaitForSingleObject(
activationEvent,
(_, timedOut) =>
{
if (!timedOut)
{
activationRequested();
}
},
null,
Timeout.Infinite,
executeOnlyOnce: false);
}
public void SignalActivate()
{
activationEvent.Set();
}
public void Dispose()
{
registeredWait?.Unregister(null);
activationEvent.Dispose();
if (IsFirstInstance)
{
try
{
mutex.ReleaseMutex();
}
catch (ApplicationException)
{
}
}
mutex.Dispose();
}
}