Is Socket.SendAsync thread safe effectively?
-
22-07-2019 - |
Question
I was fiddling with Silverlight's TCP communication and I was forced to use the System.Net.Sockets.Socket class which, on the Silverlight runtime has only asynchronous methods.
I was wondering what happens if two threads call SendAsync on a Socket instance in a very short time one from the other?
My single worry is to not have intermixed bytes going through the TCP channel.
Being an asynchronous method I suppose the message gets placed in a queue from which a single thread dequeues so no such things will happen (intermixing content of the message on the wire).
But I am not sure and the MSDN does not state anything in the method's description. Is anyone sure of this?
EDIT1 : No, locking on an object before calling SendAsync such as :
lock(this._syncObj)
{
this._socket.SendAsync(arguments);
}
will not help since this serializes the requests to send data not the data actually sent.
Solution
In order to call the SendAsync
you need first to have called ConnectAsync
with an instance of SocketAsyncEventArgs
. Its the instance of SocketAsyncEventArgs
which represents the connection between the client and server. Calling SendAsync
with the same instance of SocketAsyncEventArgs
that has just been used for an outstanding call to SendAsync
will result in an exception.
It is possible to make multiple outstanding calls to SendAsync
of the same Socket
object but only using different instances of SocketAsyncEventArgs
. For example (in a parallel universe where this might be necessay) you could be making multiple HTTP posts to the same server at the same time but on different connections. This is perfectly acceptable and normal neither client nor server will get confused about which packet is which.