-
Notifications
You must be signed in to change notification settings - Fork 2
/
NetSharedMemory.cs
71 lines (61 loc) · 1.8 KB
/
NetSharedMemory.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
using System.IO.MemoryMappedFiles;
using System.Threading;
namespace FanPlugin.Wrapper
{
public class SharedMemory<T> where T : struct
{
// Constructor
public SharedMemory(string name, int size)
{
smName = name;
smSize = size;
}
// Methods
public bool Open()
{
try
{
// Create named MMF
mmf = MemoryMappedFile.CreateOrOpen(smName, smSize);
// Create accessors to MMF
accessor = mmf.CreateViewAccessor(0, smSize,
MemoryMappedFileAccess.ReadWrite);
// Create lock
smLock = new Mutex(true, "SM_LOCK", out locked);
}
catch
{
return false;
}
return true;
}
public void Close()
{
accessor.Dispose();
mmf.Dispose();
smLock.Close();
}
public T Data
{
get
{
T dataStruct;
accessor.Read<T>(0, out dataStruct);
return dataStruct;
}
set
{
smLock.WaitOne();
accessor.Write<T>(0, ref value);
smLock.ReleaseMutex();
}
}
// Data
private string smName;
private Mutex smLock;
private int smSize;
private bool locked;
private MemoryMappedFile mmf;
private MemoryMappedViewAccessor accessor;
}
}