Skip to content

Are synchronous Sockets thread-safe? #26843

Closed
dotnet/dotnet-api-docs
#9216

Description

@AnthonySteele

Are the Socket methods Send or SendTo thread-safe? i.e. can they be used in a re-entrant manner similar to HttpClient.SendAsync and co?

Our use is for StatsD, sending data over Ip or Udp, in order to to send multiple messages to the same server.

If yes it is thread-safe, then the docs don't mention that, and they should.
If not, then we could also use a fast thread-safe socket pool instead as per #26287

Activity

  1. changed the title [-]Are Sockets thread Safe?[/-] [+]Are Sockets thread-safe?[/+] on Jul 17, 2018
  2. karelz commented on Jul 17, 2018

    @karelz
    Member

    @geoffkizer @davidsh @wfurt do you know the answer from top of your head?
    I have a feeling that they are not thread-safe.

  3. davidsh commented on Jul 17, 2018

    @davidsh
    Contributor
  4. samsosa commented on Jul 17, 2018

    @samsosa

    From https://docs.microsoft.com/en-us/windows/desktop/api/winsock/nf-winsock-sendto

    When issuing a blocking Winsock call such as sendto, Winsock may need to wait for a network event before the call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous procedure call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an ongoing blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.

  5. AnthonySteele commented on Jul 19, 2018

    @AnthonySteele
    Author

    To be clear, we are talking about the class System.Net.Sockets.Socket
    I have been shown some old docson that class that say "Thread Safety Instances of this class are thread safe."

    Are the WinSock concerns due to the .NET Socket class wrapping this?

  6. samsosa commented on Jul 19, 2018

    @samsosa

    Yes, the classic POSIX methods shall be thread-safe.

    Indeed you can safely call all functions without crashing but this doesn't mean it will work flawless in any situation.

    From http://tangentsoft.net/wskfaq/intermediate.html#threadsafety

    Is Winsock thread-safe?
    On modern Windows stacks, yes, it is, within limits.

    It is safe, for instance, to have one thread calling send() and another thread calling recv() on a single socket.

    By contrast, it’s a bad idea for two threads to both be calling send() on a single socket. This is “thread-safe” in the limited sense that your program shouldn’t crash, and you certainly shouldn’t be able to crash the kernel, which is handling these send() calls. The fact that it is “safe” doesn’t answer key questions about the actual effect of doing this. Which call’s data goes out first on the connection? Does it get interleaved somehow? Don’t do this.

  7. OccasionalDJ commented on Jul 19, 2018

    @OccasionalDJ

    but the next sentence says:

    Applications that use some kind of non-synchronous socket typically have some I/O queue already. Of particular interest in this case is overlapped I/O or I/O completion ports, because these I/O strategies are also thread-friendly. You can tell Winsock about several OVERLAPPED blocks, and Winsock will finish sending one before it moves on to the next. This means you can keep a chain of these OVERLAPPED blocks, each perhaps added to the chain by a different thread. Each thread can also call WSASend() on the block they added, making your main loop simpler.

    The c# socket class supports the old APM (async) model where the callback could be onto a different thread. Does this not suggest it will be threadsafe for multiple beginsend() on single socket anyway (as the callback would thread-hop anyway)?

    https://github.com/dotnet/corefx/blob/8747830da748f18e29469ee7f895bc8107777ad6/src/System.Net.Sockets/src/System/Net/Sockets/BaseOverlappedAsyncResult.Windows.cs#L54

    Can @geoffkizer or @stephentoub clarify this further?

  8. karelz commented on Sep 9, 2019

    @karelz
    Member

    Triage: We need validation and then proper documentation.

  9. changed the title [-]Are Sockets thread-safe?[/-] [+]Are synchronous Sockets thread-safe?[/+] on Sep 9, 2019
  10. transferred this issue fromdotnet/corefxon Jan 31, 2020
  11. added this to the 5.0 milestone on Jan 31, 2020
  12. antonfirsov commented on Jul 29, 2020

    @antonfirsov
    Contributor

    i.e. can they be used in a re-entrant manner similar to HttpClient.SendAsync and co

    @geoffkizer isn't this kind of re-entrance that you are suggesting to remove as part of #24138 ? Or am I mixing up things?

  13. geoffkizer commented on Jul 30, 2020

    @geoffkizer
    Contributor

    No, #24138 is unrelated.

  14. modified the milestones: 5.0.0, Future on Aug 11, 2020
  15. kirsan31 commented on Oct 12, 2021

    @kirsan31

    If we believe to native (windows) docs, that @samsosa is right:
    Send:

    When issuing a blocking Winsock call such as WSASend with the lpOverlapped parameter set to NULL, Winsock may need to wait for a network event before the call can complete. Winsock performs an alertable wait in this situation, which can be interrupted by an asynchronous procedure call (APC) scheduled on the same thread. Issuing another blocking Winsock call inside an APC that interrupted an ongoing blocking Winsock call on the same thread will lead to undefined behavior, and must never be attempted by Winsock clients.

    BeginSend / SendAsync:

    The order of calls made to WSASend is also the order in which the buffers are transmitted to the transport layer. WSASend should not be called on the same stream-oriented socket concurrently from different threads, because some Winsock providers may split a large send request into multiple transmissions, and this may lead to unintended data interleaving from multiple concurrent send requests on the same stream-oriented socket.

    Also, NetworkStream (simple wrapper over Socket) docs says that:

    Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization. As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required.

  16. removed their assignment
    on Jul 18, 2022
  17. added
    documentation
    on Nov 30, 2022
  18. modified the milestones: Future, 8.0.0 on Nov 30, 2022
  19. wfurt commented on Nov 30, 2022

    @wfurt
    Member

    triage: we should document current behavior. It seems like we have some gaps e.g. some operations are safe and some are not.

  20. ghost locked as resolved and limited conversation to collaborators on Sep 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Net.Socketsdocumentationquestion

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions