-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathIpcChannel.cs
More file actions
60 lines (51 loc) · 1.64 KB
/
IpcChannel.cs
File metadata and controls
60 lines (51 loc) · 1.64 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.Collections.Generic;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public class IpcChannel
{
EventWaitHandle ask;
EventWaitHandle reply;
MemoryMappedFile mmf;
public IpcChannel(int processId)
{
ask = new EventWaitHandle(false, EventResetMode.ManualReset, "ask_Scripter_IpcChannel_" + processId);
reply = new EventWaitHandle(false, EventResetMode.ManualReset, "reply_Scripter_IpcChannel_" + processId);
mmf = MemoryMappedFile.CreateOrOpen("Scripter_IpcChannel_" + processId, 1000);
}
public bool Send(String msg)
{
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
byte[] buf = Encoding.UTF8.GetBytes(msg);
byte[] bufLen = BitConverter.GetBytes(buf.Length);
stream.Write(bufLen, 0, bufLen.Length);
stream.Write(buf, 0, buf.Length);
}
ask.Set();
// Really long wait, process start can take time
bool b = reply.WaitOne(60000);
reply.Reset();
return b;
}
public bool Receive(ref String s, int timeout = 1000)
{
if (!ask.WaitOne(timeout))
return false;
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
byte[] buf = new byte[8];
stream.Read(buf, 0, 4);
int l = BitConverter.ToInt32(buf, 0);
buf = new byte[l];
stream.Read(buf, 0, l);
s = Encoding.UTF8.GetString(buf);
}
reply.Set();
ask.Reset();
return true;
}
}