-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathManager.cs
71 lines (57 loc) · 1.99 KB
/
Manager.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;
using System.IO;
using System.IO.Pipes;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Mpv.JsonIpc
{
public sealed class Manager : IDisposable, IManager
{
private readonly NamedPipeClientStream _pipe;
private StreamReader _pipeReader;
private StreamWriter _pipeWriter;
public Manager(INamedPipeFactory pipeFactory)
{
_pipe = pipeFactory.CreateNamedPipe();
}
//If we ever want to listen to random MPV actions, we can always just create a sepperate pipe for that.
//So one pipe for sending/receiving RPC call, and one just to read/oberser events from properties
public async Task<Response<T>> Execute<T>(Request request)
{
if (!_pipe.IsConnected)
{
_pipe.Connect();
_pipeReader = new StreamReader(_pipe);
_pipeWriter = new StreamWriter(_pipe);
}
var messageToSend = JsonConvert.SerializeObject(request);
await _pipeWriter.WriteLineAsync(messageToSend);
await _pipeWriter.FlushAsync(); //TODO Maybe return a flag instead of just throwing...
var counter = 0;
while (true)
{
await Task.Delay(25);
counter++;
if (counter > 1000)
{
throw new Exception("Retries maxed out");
}
var messageReceived = await _pipeReader.ReadLineAsync();
if (string.IsNullOrWhiteSpace(messageReceived))
{
continue;
}
var response = JsonConvert.DeserializeObject<Response<T>>(messageReceived);
if (response.RequestId != request.RequestId)
{
continue;
}
return response;
}
}
public void Dispose()
{
_pipe.Dispose();
}
}
}