-
Notifications
You must be signed in to change notification settings - Fork 0
/
OscMessageDispatcher.cs
83 lines (65 loc) · 1.88 KB
/
OscMessageDispatcher.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
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Suhock.Osc;
public sealed class OscMessageDispatcher
{
private readonly IOscClient _client;
private Task? _task;
public event EventHandler<OscMessage>? MessageSent;
public event EventHandler<OscMessage>? MessageReceived;
public OscMessageDispatcher(IOscClient client)
{
_client = client;
}
public bool IsRunning => _task is { IsCompleted: false };
public void Start() => Start(CancellationToken.None);
public void Start(CancellationToken cancellationToken)
{
ThrowIfRunning();
_task = new Task(ReceiveLoop, TaskCreationOptions.LongRunning);
_task.Start();
void ReceiveLoop()
{
using (_task)
{
while (true)
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
var msg = _client.Receive();
MessageReceived?.Invoke(this, msg);
}
}
}
}
public void Send(OscMessage msg)
{
ThrowIfNotRunning();
MessageSent?.Invoke(this, msg);
_client.Send(msg);
}
public Task SendAsync(OscMessage msg) => SendAsync(msg, CancellationToken.None);
public Task SendAsync(OscMessage msg, CancellationToken cancellationToken)
{
ThrowIfNotRunning();
MessageSent?.Invoke(this, msg);
return _client.SendAsync(msg, cancellationToken);
}
private void ThrowIfRunning()
{
if (IsRunning)
{
throw new InvalidOperationException("Already running");
}
}
private void ThrowIfNotRunning()
{
if (!IsRunning)
{
throw new InvalidOperationException("Not running");
}
}
}