Is UdpClient thread-safe?
In my scenario, one UdpClient.ReceiveAsync() and multiple UdpClient.SendAsync() may be executed concurrently. Will this cause any race conditions?
No it's not. Take a look at the source. https://github.com/dotnet/corefx/blob/eebe43224d8994b5b47bc2906c271ea6f256728b/src/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs#L18 The Buffer ist used in e.g. BeginReceive which is in turn used in ReceiveAsync. https://github.com/dotnet/corefx/blob/eebe43224d8994b5b47bc2906c271ea6f256728b/src/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs#L392
Yes it indicates multiple calls to ReceiveAsync() may not be thread-safe. But in my scenario, only one thread will call ReceiveAsync() while multiple threads may call SendAsync().
@chuyangliu - It uses Socket underneath, so the proper question is "is Socket safe for multiple SendAsync calls?" (I don't know the true answer to that, unfortunately).
Looks like Socket is thread-safe per MSDN?
Though UdpClient is a thin wrapper for Socket, it still accesses some shared class members inside BeginSend() so I'm not so sure about it.
@chuyangliu you can use multiple instances of Socket concurrently, but calling a single instance of Socket concurrently is not thread-safe for all scenarios.
Currently, particular to the connectionless (i.e. UDP) methods, they are not currently thread-safe if you use the socket without binding it first.