Threadsafe async code design
With a single UDP/TCP client or serial connection, I want to send and receive concurrently. The sending and receiving code is asynchronous so locks are out of the question. Trying to follow closely with a hosted app and dependency injection. Been stuck thinking about it for a few hours because every solution I've been able to come up has a gotcha.
Attached is the logic
Thought splitting into two classes would be good but if I'm working with the same UDP/TCP/serial connection then it goes back to the locking issue. Adding a third class for message queueing could work but then you might end up waiting for bytes with outgoing messages in queue that could've been sent by the time you receive the next bytes.
3 Replies
It looks like all of the important code is in “IProtocol”, so that’s sort of necessary to see. File attachments aren’t a great way to share $code
To post C# code type the following:
```cs
// code here
```
Get an example by typing
$codegif
in chat
For longer snippets, use: https://paste.mod.gg/there are a few things you can do
either you use SemaphoreSlim, which has WaitAsync
or you serialize actions to the channel with you favorite primitive (like channels)
or you can can transform commands in messages and serialize that
and probably some other stuff too, more or less complex