Use CancellationToken.UnsafeRegister in a few more places (dotnet/corefx#37551)
authorStephen Toub <stoub@microsoft.com>
Thu, 16 May 2019 18:08:10 +0000 (11:08 -0700)
committerGitHub <noreply@github.com>
Thu, 16 May 2019 18:08:10 +0000 (11:08 -0700)
commit377c37c140b3fbedeb2ed1e1694783f65cb71733
tree89321415ca70731cc8b27790f481b55beac56a0c
parent8a551a0cd1a8b0c99738fe15ba53a15345c46d65
Use CancellationToken.UnsafeRegister in a few more places (dotnet/corefx#37551)

CancellationToken.Register captures the current ExecutionContext and uses it to invoke the callback if/when it's invoked.  That's generally desirable and is the right default, but in cases where we know for certain the callback doesn't care about EC (e.g. we're not invoking any 3rd-party code), we can use UnsafeRegister instead (newly added in 3.0), which skips capturing the ExecutionContext, as if Capture returned null.  This helps few a couple of small costs:
- Avoids thread local lookups to capture the current EC.
- Avoids additional delegate invocations and thread local gets/sets to invoke the callback with the captured EC.
- Avoids holding on to the EC in case it's needed, which can potentially keep alive an unbounded amount of state due to AsyncLocals.

Commit migrated from https://github.com/dotnet/corefx/commit/b1a1bfa0997ce35e8540fbbe74276858e315807e
src/libraries/Common/src/System/Net/WebSockets/ManagedWebSocket.cs
src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Linux.cs
src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs
src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs
src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs
src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectHelper.cs
src/libraries/System.Net.WebSockets.WebSocketProtocol/src/System.Net.WebSockets.WebSocketProtocol.csproj
src/libraries/System.Net.WebSockets.WebSocketProtocol/src/System/Net/WebSockets/ManagedWebSocketExtensions.cs
src/libraries/System.Net.WebSockets.WebSocketProtocol/src/System/Net/WebSockets/ManagedWebSocketExtensions.netstandard.cs [new file with mode: 0644]
src/libraries/System.Threading.Tasks.Parallel/src/System/Threading/Tasks/Parallel.cs