| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | namespace System.Threading.Tasks |
| | | 5 | | { |
| | | 6 | | /// <summary> |
| | | 7 | | /// A <see cref="TaskCompletionSource{TResult}"/> that supports cancellation registration so that any |
| | | 8 | | /// <seealso cref="OperationCanceledException"/>s contain the relevant <see cref="CancellationToken"/>, |
| | | 9 | | /// while also avoiding unnecessary allocations for closure captures. |
| | | 10 | | /// </summary> |
| | | 11 | | internal class TaskCompletionSourceWithCancellation<T> : TaskCompletionSource<T> |
| | | 12 | | { |
| | 0 | 13 | | public TaskCompletionSourceWithCancellation() : base(TaskCreationOptions.RunContinuationsAsynchronously) |
| | 0 | 14 | | { |
| | 0 | 15 | | } |
| | | 16 | | |
| | | 17 | | public async ValueTask<T> WaitWithCancellationAsync(CancellationToken cancellationToken) |
| | 0 | 18 | | { |
| | 0 | 19 | | using (cancellationToken.UnsafeRegister(static (s, cancellationToken) => ((TaskCompletionSourceWithCancellat |
| | 0 | 20 | | { |
| | 0 | 21 | | return await Task.ConfigureAwait(false); |
| | | 22 | | } |
| | 0 | 23 | | } |
| | | 24 | | |
| | | 25 | | public T WaitWithCancellation(CancellationToken cancellationToken) |
| | 0 | 26 | | { |
| | 0 | 27 | | using (cancellationToken.UnsafeRegister(static (s, cancellationToken) => ((TaskCompletionSourceWithCancellat |
| | 0 | 28 | | { |
| | 0 | 29 | | return Task.GetAwaiter().GetResult(); |
| | | 30 | | } |
| | 0 | 31 | | } |
| | | 32 | | |
| | | 33 | | public ValueTask<T> WaitWithCancellationAsync(bool async, CancellationToken cancellationToken) |
| | 0 | 34 | | { |
| | 0 | 35 | | return async ? |
| | 0 | 36 | | WaitWithCancellationAsync(cancellationToken) : |
| | 0 | 37 | | new ValueTask<T>(WaitWithCancellation(cancellationToken)); |
| | 0 | 38 | | } |
| | | 39 | | } |
| | | 40 | | } |