/
InterProcessLock.cs
48 lines (40 loc) · 1.41 KB
/
InterProcessLock.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
using System;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;
namespace Capture
{
public class InterProcessLock : IDisposable
{
public Mutex Mutex { get; private set; }
public bool IsAcquired { get; private set; }
public InterProcessLock(string name, TimeSpan timeout)
{
bool created;
var security = new MutexSecurity();
security.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow));
Mutex = new Mutex(false, name, out created, security);
IsAcquired = Mutex.WaitOne(timeout);
}
#region IDisposable Members
public void Dispose()
{
if (IsAcquired)
{
Mutex.ReleaseMutex();
IsAcquired = false;
}
}
#endregion
public static bool TryCreate(string name, TimeSpan timeout, out InterProcessLock thelock)
{
thelock = new InterProcessLock(name, timeout);
return thelock.IsAcquired;
}
public static bool TryCreate(string name, int timeout, out InterProcessLock thelock)
{
thelock = new InterProcessLock(name, TimeSpan.FromMilliseconds(timeout));
return thelock.IsAcquired;
}
}
}