- Avoid ThreadPool-related allocations via IThreadPoolWorkItem. We already had a fairly low allocation profile on most channels, thanks to an IValueTaskSource implementation. This extends that implementation with an IThreadPoolWorkItem implementation so that when we do need to queue to the pool (e.g. to support RunContinuationsAsynchronously, on writes on the bounded queue, etc.), we can do so without incurring additional allocation.
- Avoid ExecutionContext costs with CancellationToken.UnsafeRegister. Minor savings when a cancelable token is provided; we don't need to flow context as all we're doing is completing another object.
Commit migrated from https://github.com/dotnet/corefx/commit/89ab1e83a7e00d869e1580151e24f01226acaf3f
* Fix a few XML comments
* Rename internal Dequeue<T> to Deque<T>
Just to better conform to the typical spelling.
* Fix includes ordering in Channels project file
* Fix continuation scheduling with non-default TaskScheduler and default SyncContext
When {Unsafe}OnCompleted is called on an AsyncOperation in Channels, without ConfigureAwait(false), we look to see if there's a current non-default SynchronizationContext, and if there isn't, then a current non-default TaskScheduler. That's stored for later when the operation is completed. However, if as OnCompleted is being called the operation is completed, then rather than using this captured context or scheduler later, the continuation is immediately queued to the appropriate context. When that happens, if the current SynchronizationContext was non-null but still the default (an instance of the base class), we're incorrectly ignoring whatever TaskScheduler may have been present, and end up queueing to the thread pool rather than to that scheduler.
The fix is just to ensure that, in that case, we don't pay attention to the default SynchronizationContext. This does so and adds a test.
* Add a test with both non-default SyncContext and TaskScheduler set
Validate that, when there's both a non-default SyncContext and a non-default TaskScheduler, we prefer the SyncContext.
Commit migrated from https://github.com/dotnet/corefx/commit/207a50b7866cef71ead4ff70e7384e77a62b985a
The synchronization in System.Threading.Channel's AsyncOperation was messed up after the switch to ValueTask, in particular in the face of cancellation. The key issue was that we were using two different fields to represent operation completion, which meant they weren't being updated atomically and allowed for things to get out of sync.
For example, a thread could be completing an operation and after setting Completed but before setting the s_completedSentinel, another thread could check IsCompleted, call GetResult, make the operation available for pooled reuse, another renter of it could claim it, and then the original thread could end up continuing and storing the s_completedSentinel into an object it no longer owns. Running the perf or stress tests would cause asserts to fire sporadically.
This commit restructures AsyncOperation to avoid such issues. Now the _continuation field is the sole source of truth as to whether the operation has completed. This has the nice side-effect of reducing interlocked operations for the common path (e.g. using a pooled object). It also fixes the issues that prevented us from using pooling in BoundedChannel, so the change also enables that.
Commit migrated from https://github.com/dotnet/corefx/commit/fb3b7daa44cd5e3e4a8d1ac20d3c3f1dbae8a266
This commit does several things:
- Exposes the new `ValueTask` extensibility model being added in coreclr. The ValueTask-related files will separately be mirrored over to corefx to enable the netstandard build of System.Threading.Tasks.Extensions.
- Adapts all `Stream`-derived types to return `ValueTask` instead of `Task` from `WriteAsync`.
- Changes the new `WebSocket` `SendAsync` method to return `ValueTask` instead of `Task`, and updates the `ManagedWebSocket` implementation accordingly. Most `SendAsync`s on `ManagedWebSocket` should now return a `ValueTask` that's either completed synchronously (no allocation) or using a pooled object. It now uses the underlying transport's new `WriteAsync` overload that returns `ValueTask`.
- Switches more uses of `ReadAsync` and `WriteAsync` over to the new overloads, including in Process, DeflateStream, BrotliStream, File, HttpClient, SslStream, WebClient, BufferedStream, CryptoStream,
- Removed some unnecessary array clearing from various routines using ArrayPool (after the clearing was added we changed our minds and decided clearing was only necessary in very specific circumstances)
- Implements a custom `IValueTaskSource` in Socket, such that async receives and sends become allocation-free (ammortized). `NetworkStream` then inherits this functionality, such that its new `ReadAsync` and `WriteAsync` are also allocation-free (in the unbounded channel implementations; we can subsequently add it in for bounded).
- Implements a custom `IValueTaskSource` in System.Threading.Channels, such that reading and writing are ammortized allocation-free up to one concurrent reader and writer.
- A few random things I noticed as I was going through, e.g. missing ConfigureAwait, some incorrect synchronization in tests, etc.
- Adds a ton of new tests, mainly in System.Threading.Tasks.Extensions, System.Threading.Channels, and System.Net.Sockets.
Commit migrated from https://github.com/dotnet/corefx/commit/6d1671b2cfcf130b7bc6c059bb0508073426532a
* Fix some Channel issues
These issues caught during the code review of the Channel code.
* Fix reader waiter waking inside the lock
* Addressing the feedback
* tag the problematic line of code with the tracking issue
* revert BoundedChannel changes
* remove empty lines
Commit migrated from https://github.com/dotnet/corefx/commit/b8a15a768b8255096fc87dd9cb9f33cdb4a25208
In the API review, we'd said to remove ReadAsync if we could, as we didn't like that it encouraged exceptions as control flow, due to exceptions getting thrown when attempting to read from a completed channel.
However, removing it is problematic for a few reasons:
- While for most channels its behavior can be achieved external to the channels on top of TryRead and WaitToReadAsync, that's not the case for UnbufferedChannel. UnbufferedChannel.ReadAsync provides unique functionality that can only be achieved from within the implementation, as reads need to exist concurrently with writes in order for them to pair up.
- Channels in go don't have the notion of completion, which means the ReadAsync equivalent is very common there. Any code written in that style and trying to port to this will expect a similar function but will instead be forced to emulate it with WaitToReadAsync/TryRead.
As such, I'm putting it back as a base virtual method and an override just on UnbufferedChannel's implementation.
Commit migrated from https://github.com/dotnet/corefx/commit/3c73f4621fe891aa25e97be2bbf772d7a747d263