runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Is UdpClient thread-safe?

Open chynl opened this issue 7 years ago • 5 comments

In my scenario, one UdpClient.ReceiveAsync() and multiple UdpClient.SendAsync() may be executed concurrently. Will this cause any race conditions?

chynl avatar Jun 24 '19 17:06 chynl

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

Tornhoof avatar Jun 24 '19 18:06 Tornhoof

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().

chynl avatar Jun 24 '19 18:06 chynl

@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).

Clockwork-Muse avatar Jun 24 '19 18:06 Clockwork-Muse

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.

chynl avatar Jun 24 '19 18:06 chynl

@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.

scalablecory avatar Sep 09 '19 17:09 scalablecory