📄
OutGridTree.Window/RpcService.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
using System; using System.IO; using System.IO.Pipes; using System.Management.Automation; using System.Text; using System.Threading; namespace OutGridTree.Window; internal sealed class RpcService { public event Action<object?>? RecordReceived; private NamedPipeClientStream? pipe; private readonly CancellationTokenSource cts = new(); private Thread? thread; public void Start(string pipeName) { pipe = new(".", pipeName, PipeDirection.In); thread = new(Run); thread.Start(); } private void Run() { if (pipe is null) { return; } pipe.Connect(); var reader = new StreamReader(pipe); while (reader.ReadLine(cts.Token) is string line) { var record = PSSerializer.Deserialize(Encoding.UTF8.GetString(Convert.FromBase64String(line))); RecordReceived?.Invoke(record); } } public void Stop() { cts.Cancel(); thread?.Join(); pipe?.Dispose(); } } file static class StreamReaderExtensions { public static string? ReadLine(this StreamReader reader, CancellationToken cancellationToken) { var valueTask = reader.ReadLineAsync(cancellationToken); if (valueTask.IsCompletedSuccessfully) { return valueTask.Result; } var task = valueTask.AsTask(); task.Wait(cancellationToken); return task.Result; } }