none
Thread Safety of UdpClient.Send() RRS feed

  • Question

  • I'm writing a C# application right now and I'm wondering about the thread safety of the UdpClient class, mainly with the Send() method.  My architecture consist of an app that has one thread thread do all of the reading (with Receive()), but there are many other thread that need to write data to the networking using that same UdpClient instance.

    So my question really is: Can I just call the UdpClient.Send() method from many other threads (at the same time), and is it guaranteed that all of my data will make it to the network?  Or should I use something like a ConcurrentQueue structure to queue up messages instead and Send() them in the thread where Receive() is reading them?

    Sunday, August 28, 2016 12:04 AM

Answers

  • The documentation for UdpClient mentions that any instance members are not guaranteed to be thread safe: https://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient(v=vs.110).aspx#Anchor_9. And because the documentation for Send does not specify anything else, I think that you should assume that the function is not thread safe. Therefore, if this object has to be shared between threads (instead of creating separate objects), then at least consider some locking mechanism. The simplest is: ‘lock(c) { c.Send(…); }’, where c is the UdpClient.

    • Proposed as answer by Hart Wang Friday, September 2, 2016 7:48 AM
    • Marked as answer by def-pri-pub Saturday, September 3, 2016 5:24 AM
    Sunday, August 28, 2016 7:13 AM