locked
Thread safety of socket.BeginSend()

    Question

  • I've read that "The Socket class is not thread-safe at the instance level." (http://www.thecodeproject.com/csharp/XYNetSocket.asp). My question is, can one BeginSend() operation interrupt a previous BeginSend() on the same socket instance?
    What are the implications of concurrent sockets access with BeginSend()? Do I need to lock the socket object before I call BeginSend()?

    Another quick question, according to MSDN documentation, "You can create a callback method that implements the AsyncCallback delegate and pass its name to the BeginSend
    method.". Do I HAVE to have a callback method, and what are the implications of not having a callback method?
    Thanks in advance...
    Saturday, October 29, 2005 7:51 PM

Answers

  • 1. You can queue multiple BeginSends at the same time. YOu don't need to lock
    2. If you don't create a callback method, how do you know when the send is
    successful? You may want to ignore the success - more like a fire and forget - method, but then you at least need to know when it is safe to end your program.
    3. The other thing you can do is use the IAsyncResult that you get from BeginSend. You can use the WaitHandle to wait for the operation to complete.
    But that defeats the whole purpose of using Async in the first place.
    4. My recommendation is to use a callback, and make sure that the
    callback is called and the number of bytes you sent is actually sent and
    gracefuly end the send operation.
    Saturday, October 29, 2005 8:57 PM
    Moderator

All replies

  • 1. You can queue multiple BeginSends at the same time. YOu don't need to lock
    2. If you don't create a callback method, how do you know when the send is
    successful? You may want to ignore the success - more like a fire and forget - method, but then you at least need to know when it is safe to end your program.
    3. The other thing you can do is use the IAsyncResult that you get from BeginSend. You can use the WaitHandle to wait for the operation to complete.
    But that defeats the whole purpose of using Async in the first place.
    4. My recommendation is to use a callback, and make sure that the
    callback is called and the number of bytes you sent is actually sent and
    gracefuly end the send operation.
    Saturday, October 29, 2005 8:57 PM
    Moderator
  • Sometimes there is some confusion around how many times you callback function will be executed.  The logic is as expected - your callback function will be called once for each call made to BeginSend.  These semanctics are true for all async calls.

    Monday, October 31, 2005 6:05 AM