views:

76

answers:

2

hello stack overflow!

i have a socket, im using to send large buffers through, if ill do something like

// may be accsed form a a lot of threads
void Send(byte[] buffer)
{
  m_socket.BeginSend(buffer ... , SendCallback);
}

void SendCallback()
{
  m_socket.EndSend()

  // if not done sending- send the reset
  m_socket.BeginSend()
}

my question is: will this work from a multithreading stand point, or will the buffers interleave?

A: 

Quoting MSDN:

If you perform multiple asynchronous operations on a socket, they do not necessarily complete in the order in which they are started.

But if you are sending blocks of data from multiple threads, what is your definition of 'order' anyway?

Henk Holterman
if i have to messages: "aaaa" and "bbbb" i wont the reciver to get: "aaaabbbb" or "bbbbaaaa", but not "aabbaabb" if the socket's sending buffer is 2 bytes big.
Hellfrost
+1  A: 

It appears that this is thread-safe.

Since your delegate to "SendCallback" is executed on a new thread, I would presume that EndSend() can tell which asynchronous operation you are ending based on the current thread context.

See the MSDN "Best Practices" for the asynchronous programming model:

Simultaneously Executing Operations

If your class supports multiple concurrent invocations, enable the developer to track each invocation separately by defining the MethodNameAsync overload that takes an object-valued state parameter, or task ID, called userSuppliedState. This parameter should always be the last parameter in the MethodNameAsync method's signature.

http://msdn.microsoft.com/en-us/library/ms228974.aspx

Sam
look at my comment to henk
Hellfrost