Thread-lock by ParameterInstance.lockObject, does it work?
I've googled far and wide and found no answer to this. I am programming my own little Tcp library to make it easy for myself. On the server I have a 'ConnectedClient' object that has a socket and a network stream. On the server static class I have a Send function that sends a length-prefixed stream. I want the stream to be thread safe, but for each client. Would this work for that?
Send(ConnectedClient client, ...(rest of parameters nor relevant))
{
lock (client.lockObject)
{
// Wri开发者_Go百科ting to stream thread-safely I hope...
}
}
I hope I made myself clear enough, if not, just ask for more details.
It looks like you are writing some kind of multiplexer. Indeed, that should work fine as long as you write an entire payload (and length-prefix) within a single lock
, and as long as the lockObject
is representative of the mutual-exclusive resource (i.e. must be a common lockObject
for all clients that we don't want to collide).
Perhaps the trickier question is: are you going to read the reply within that method (success/return-value/critical-fail), or are you going to read the reply asynchronously, and let the next writer write to the stream while the first message is flying...
For comparison, when writing BookSleeve (a redis multiplexer, full source available if you want some reference code), I chose a different strategy: one dedicated thread to do all the writing to the thread, with all the callers simply appending to a thread-safe queue; that way, even if there is a backlog of work, the callers aren't delayed.
精彩评论