开发者

.Net async Socket multi-threaded sending

开发者 https://www.devze.com 2023-01-05 10:54 出处:网络
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

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)
{开发者_如何学Go
  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?


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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号