Consider the Socket.BeginSend()
method. If two thread pool threads were to call this method simultaneously, would their respective messages end up mixing with each other or does the socket class keep this from happening?
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
.NET Socket instances are not thread-safe in that simultaneous calls to some methods (the same or different ones) may cause inconsistent state. However, the
BeginSend()
andBeginReceive()
methods are thread-safe with respect to themselves.It is safe to have multiple outstanding calls to each (or both).
In the case of
BeginReceive()
, they will be serviced when data is available in the order called. This can be useful if, for example, your processing is lengthy but you want other receives to occur as quickly as possible. Of course in this case you may have your code processing multiple receipts simultaneously and you may need your own synchronization logic to protect your application state.In the case of
BeginSend()
, each call will attempt to push the sent data into the socket buffer, and as soon as it is accepted there, your callback will be called (where you will callEndSend()
). If there is insufficient buffer space for any call, it will block.Note: don't assume that the default 8k buffer means "I can quickly call
BeginSend()
with exactly 8k of data, then it will block," as the following are true:The 8K is a "nominal size" number, and the buffer may shrink and grow somewhat
As you are queing up the 8K worth of calls, data will be being sent on the network reducing that 8K of queued data
In general:
If you call
BeginSend()
several times within a thread, you are assured that the sends will leave the machine in the order they were called.If you call
BeginSend()
from several threads, there is no guarantee of order unless you use some other blocking mechanism to force the actual calls to occur in some specific order. Each call however will send its data properly in one contiguous stream of network bytes.I found a smiliar post on the MSDN forum which seems to answer to your question.
Edit:
Even more interesting informations:
If you scroll down a bit in the Remark section of the MSDN doc BeginSend(), you will find interesting use of callback methods that could be relevant for you.