|
| 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 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Diagnostics; |
| 7 | +using System.IO; |
| 8 | +using System.Runtime.InteropServices; |
| 9 | +using System.Threading; |
| 10 | +using System.Threading.Tasks; |
| 11 | +using System.Threading.Tasks.Sources; |
| 12 | + |
| 13 | +namespace Microsoft.Win32.SafeHandles |
| 14 | +{ |
| 15 | + public sealed partial class SafeFileHandle : SafeHandleZeroOrMinusOneIsInvalid |
| 16 | + { |
| 17 | + private ThreadPoolValueTaskSource? _reusableThreadPoolValueTaskSource; // reusable ThreadPoolValueTaskSource that is currently NOT being used |
| 18 | + |
| 19 | + // Rent the reusable ThreadPoolValueTaskSource, or create a new one to use if we couldn't get one (which |
| 20 | + // should only happen on first use or if the SafeFileHandle is being used concurrently). |
| 21 | + internal ThreadPoolValueTaskSource GetThreadPoolValueTaskSource() => |
| 22 | + Interlocked.Exchange(ref _reusableThreadPoolValueTaskSource, null) ?? new ThreadPoolValueTaskSource(this); |
| 23 | + |
| 24 | + private void TryToReuse(ThreadPoolValueTaskSource source) |
| 25 | + { |
| 26 | + Interlocked.CompareExchange(ref _reusableThreadPoolValueTaskSource, source, null); |
| 27 | + } |
| 28 | + |
| 29 | + /// <summary> |
| 30 | + /// A reusable <see cref="IValueTaskSource"/> implementation that |
| 31 | + /// queues asynchronous <see cref="RandomAccess"/> operations to |
| 32 | + /// be completed synchronously on the thread pool. |
| 33 | + /// </summary> |
| 34 | + internal sealed class ThreadPoolValueTaskSource : IThreadPoolWorkItem, IValueTaskSource<int>, IValueTaskSource<long> |
| 35 | + { |
| 36 | + private readonly SafeFileHandle _fileHandle; |
| 37 | + private ManualResetValueTaskSourceCore<long> _source; |
| 38 | + private Operation _operation = Operation.None; |
| 39 | + private ExecutionContext? _context; |
| 40 | + |
| 41 | + // These fields store the parameters for the operation. |
| 42 | + // The first two are common for all kinds of operations. |
| 43 | + private long _fileOffset; |
| 44 | + private CancellationToken _cancellationToken; |
| 45 | + // Used by simple reads and writes. Will be unsafely cast to a memory when performing a read. |
| 46 | + private ReadOnlyMemory<byte> _singleSegment; |
| 47 | + private IReadOnlyList<Memory<byte>>? _readScatterBuffers; |
| 48 | + private IReadOnlyList<ReadOnlyMemory<byte>>? _writeGatherBuffers; |
| 49 | + |
| 50 | + internal ThreadPoolValueTaskSource(SafeFileHandle fileHandle) |
| 51 | + { |
| 52 | + _fileHandle = fileHandle; |
| 53 | + } |
| 54 | + |
| 55 | + [Conditional("DEBUG")] |
| 56 | + private void ValidateInvariants() |
| 57 | + { |
| 58 | + Operation op = _operation; |
| 59 | + Debug.Assert(op == Operation.None, $"An operation was queued before the previous {op}'s completion."); |
| 60 | + } |
| 61 | + |
| 62 | + private long GetResultAndRelease(short token) |
| 63 | + { |
| 64 | + try |
| 65 | + { |
| 66 | + return _source.GetResult(token); |
| 67 | + } |
| 68 | + finally |
| 69 | + { |
| 70 | + _source.Reset(); |
| 71 | + _fileHandle.TryToReuse(this); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + public ValueTaskSourceStatus GetStatus(short token) => _source.GetStatus(token); |
| 76 | + public void OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) => |
| 77 | + _source.OnCompleted(continuation, state, token, flags); |
| 78 | + int IValueTaskSource<int>.GetResult(short token) => (int) GetResultAndRelease(token); |
| 79 | + long IValueTaskSource<long>.GetResult(short token) => GetResultAndRelease(token); |
| 80 | + |
| 81 | + private void ExecuteInternal() |
| 82 | + { |
| 83 | + Debug.Assert(_operation >= Operation.Read && _operation <= Operation.WriteGather); |
| 84 | + |
| 85 | + long result = 0; |
| 86 | + Exception? exception = null; |
| 87 | + try |
| 88 | + { |
| 89 | + // This is the operation's last chance to be canceled. |
| 90 | + if (_cancellationToken.IsCancellationRequested) |
| 91 | + { |
| 92 | + exception = new OperationCanceledException(_cancellationToken); |
| 93 | + } |
| 94 | + else |
| 95 | + { |
| 96 | + switch (_operation) |
| 97 | + { |
| 98 | + case Operation.Read: |
| 99 | + Memory<byte> writableSingleSegment = MemoryMarshal.AsMemory(_singleSegment); |
| 100 | + result = RandomAccess.ReadAtOffset(_fileHandle, writableSingleSegment.Span, _fileOffset); |
| 101 | + break; |
| 102 | + case Operation.Write: |
| 103 | + result = RandomAccess.WriteAtOffset(_fileHandle, _singleSegment.Span, _fileOffset); |
| 104 | + break; |
| 105 | + case Operation.ReadScatter: |
| 106 | + Debug.Assert(_readScatterBuffers != null); |
| 107 | + result = RandomAccess.ReadScatterAtOffset(_fileHandle, _readScatterBuffers, _fileOffset); |
| 108 | + break; |
| 109 | + case Operation.WriteGather: |
| 110 | + Debug.Assert(_writeGatherBuffers != null); |
| 111 | + result = RandomAccess.WriteGatherAtOffset(_fileHandle, _writeGatherBuffers, _fileOffset); |
| 112 | + break; |
| 113 | + } |
| 114 | + } |
| 115 | + } |
| 116 | + catch (Exception e) |
| 117 | + { |
| 118 | + exception = e; |
| 119 | + } |
| 120 | + finally |
| 121 | + { |
| 122 | + _operation = Operation.None; |
| 123 | + _context = null; |
| 124 | + _cancellationToken = default; |
| 125 | + _singleSegment = default; |
| 126 | + _readScatterBuffers = null; |
| 127 | + _writeGatherBuffers = null; |
| 128 | + } |
| 129 | + |
| 130 | + if (exception == null) |
| 131 | + { |
| 132 | + _source.SetResult(result); |
| 133 | + } |
| 134 | + else |
| 135 | + { |
| 136 | + _source.SetException(exception); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + void IThreadPoolWorkItem.Execute() |
| 141 | + { |
| 142 | + if (_context == null || _context.IsDefault) |
| 143 | + { |
| 144 | + ExecuteInternal(); |
| 145 | + } |
| 146 | + else |
| 147 | + { |
| 148 | + ExecutionContext.RunForThreadPoolUnsafe(_context, static x => x.ExecuteInternal(), this); |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + private void QueueToThreadPool() |
| 153 | + { |
| 154 | + _context = ExecutionContext.Capture(); |
| 155 | + ThreadPool.UnsafeQueueUserWorkItem(this, preferLocal: true); |
| 156 | + } |
| 157 | + |
| 158 | + public ValueTask<int> QueueRead(Memory<byte> buffer, long fileOffset, CancellationToken cancellationToken) |
| 159 | + { |
| 160 | + ValidateInvariants(); |
| 161 | + |
| 162 | + _operation = Operation.Read; |
| 163 | + _singleSegment = buffer; |
| 164 | + _fileOffset = fileOffset; |
| 165 | + _cancellationToken = cancellationToken; |
| 166 | + QueueToThreadPool(); |
| 167 | + |
| 168 | + return new ValueTask<int>(this, _source.Version); |
| 169 | + } |
| 170 | + |
| 171 | + public ValueTask<int> QueueWrite(ReadOnlyMemory<byte> buffer, long fileOffset, CancellationToken cancellationToken) |
| 172 | + { |
| 173 | + ValidateInvariants(); |
| 174 | + |
| 175 | + _operation = Operation.Write; |
| 176 | + _singleSegment = buffer; |
| 177 | + _fileOffset = fileOffset; |
| 178 | + _cancellationToken = cancellationToken; |
| 179 | + QueueToThreadPool(); |
| 180 | + |
| 181 | + return new ValueTask<int>(this, _source.Version); |
| 182 | + } |
| 183 | + |
| 184 | + public ValueTask<long> QueueReadScatter(IReadOnlyList<Memory<byte>> buffers, long fileOffset, CancellationToken cancellationToken) |
| 185 | + { |
| 186 | + ValidateInvariants(); |
| 187 | + |
| 188 | + _operation = Operation.ReadScatter; |
| 189 | + _readScatterBuffers = buffers; |
| 190 | + _fileOffset = fileOffset; |
| 191 | + _cancellationToken = cancellationToken; |
| 192 | + QueueToThreadPool(); |
| 193 | + |
| 194 | + return new ValueTask<long>(this, _source.Version); |
| 195 | + } |
| 196 | + |
| 197 | + public ValueTask<long> QueueWriteGather(IReadOnlyList<ReadOnlyMemory<byte>> buffers, long fileOffset, CancellationToken cancellationToken) |
| 198 | + { |
| 199 | + ValidateInvariants(); |
| 200 | + |
| 201 | + _operation = Operation.WriteGather; |
| 202 | + _writeGatherBuffers = buffers; |
| 203 | + _fileOffset = fileOffset; |
| 204 | + _cancellationToken = cancellationToken; |
| 205 | + QueueToThreadPool(); |
| 206 | + |
| 207 | + return new ValueTask<long>(this, _source.Version); |
| 208 | + } |
| 209 | + |
| 210 | + private enum Operation : byte |
| 211 | + { |
| 212 | + None, |
| 213 | + Read, |
| 214 | + Write, |
| 215 | + ReadScatter, |
| 216 | + WriteGather |
| 217 | + } |
| 218 | + } |
| 219 | + } |
| 220 | +} |
0 commit comments