Remove lock allocation from SafeSocketHandle on Windows (#32275)
authorStephen Toub <stoub@microsoft.com>
Fri, 14 Feb 2020 16:12:15 +0000 (08:12 -0800)
committerGitHub <noreply@github.com>
Fri, 14 Feb 2020 16:12:15 +0000 (08:12 -0800)
commiteedeeb628aa703a114940fd40cf0c538f9ec454b
treef9e19cb4b813cb885d6073fde97ea194a8b4661a
parent8f546c925918741f604a58b945545bad4355aba6
Remove lock allocation from SafeSocketHandle on Windows (#32275)

The first time a Socket is used, we bind its handle to the ThreadPool for overlapped I/O.  In order to avoid this happening on multiple threads concurrently if multiple threads concurrently race to perform this initialization, we take a lock.  We currently allocate an object and store it for the lifetime of the Socket, purely to do this one-time synchronization, after which the object is useless.  While in general we prefer not to lock on `this` (in order to avoid any issues that might occur from an external consumer also locking on the same object), the chances of someone locking on this object are slim to none, and even if they did, it wouldn't make any difference once the socket was already initialized, and even if the socket wasn't yet initialized, it would only be a one-time contention, without lock ordering concerns.
src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Windows.cs