Stream.cs 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341
  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. // See the LICENSE file in the project root for more information.
  4. /*============================================================
  5. **
  6. **
  7. **
  8. **
  9. **
  10. ** Purpose: Abstract base class for all Streams. Provides
  11. ** default implementations of asynchronous reads & writes, in
  12. ** terms of the synchronous reads & writes (and vice versa).
  13. **
  14. **
  15. ===========================================================*/
  16. using System.Buffers;
  17. using System.Diagnostics;
  18. using System.Runtime.CompilerServices;
  19. using System.Runtime.ExceptionServices;
  20. using System.Runtime.InteropServices;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. namespace System.IO
  24. {
  25. public abstract partial class Stream : MarshalByRefObject, IDisposable, IAsyncDisposable
  26. {
  27. public static readonly Stream Null = new NullStream();
  28. // We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K).
  29. // The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant
  30. // improvement in Copy performance.
  31. private const int DefaultCopyBufferSize = 81920;
  32. // To implement Async IO operations on streams that don't support async IO
  33. private ReadWriteTask _activeReadWriteTask;
  34. private SemaphoreSlim _asyncActiveSemaphore;
  35. internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
  36. {
  37. // Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's
  38. // WaitHandle, we don't need to worry about Disposing it.
  39. return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
  40. }
  41. public abstract bool CanRead
  42. {
  43. get;
  44. }
  45. // If CanSeek is false, Position, Seek, Length, and SetLength should throw.
  46. public abstract bool CanSeek
  47. {
  48. get;
  49. }
  50. public virtual bool CanTimeout
  51. {
  52. get
  53. {
  54. return false;
  55. }
  56. }
  57. public abstract bool CanWrite
  58. {
  59. get;
  60. }
  61. public abstract long Length
  62. {
  63. get;
  64. }
  65. public abstract long Position
  66. {
  67. get;
  68. set;
  69. }
  70. public virtual int ReadTimeout
  71. {
  72. get
  73. {
  74. throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
  75. }
  76. set
  77. {
  78. throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
  79. }
  80. }
  81. public virtual int WriteTimeout
  82. {
  83. get
  84. {
  85. throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
  86. }
  87. set
  88. {
  89. throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
  90. }
  91. }
  92. public Task CopyToAsync(Stream destination)
  93. {
  94. int bufferSize = GetCopyBufferSize();
  95. return CopyToAsync(destination, bufferSize);
  96. }
  97. public Task CopyToAsync(Stream destination, int bufferSize)
  98. {
  99. return CopyToAsync(destination, bufferSize, CancellationToken.None);
  100. }
  101. public Task CopyToAsync(Stream destination, CancellationToken cancellationToken)
  102. {
  103. int bufferSize = GetCopyBufferSize();
  104. return CopyToAsync(destination, bufferSize, cancellationToken);
  105. }
  106. public virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
  107. {
  108. StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
  109. return CopyToAsyncInternal(destination, bufferSize, cancellationToken);
  110. }
  111. private async Task CopyToAsyncInternal(Stream destination, int bufferSize, CancellationToken cancellationToken)
  112. {
  113. byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
  114. try
  115. {
  116. while (true)
  117. {
  118. int bytesRead = await ReadAsync(new Memory<byte>(buffer), cancellationToken).ConfigureAwait(false);
  119. if (bytesRead == 0) break;
  120. await destination.WriteAsync(new ReadOnlyMemory<byte>(buffer, 0, bytesRead), cancellationToken).ConfigureAwait(false);
  121. }
  122. }
  123. finally
  124. {
  125. ArrayPool<byte>.Shared.Return(buffer);
  126. }
  127. }
  128. // Reads the bytes from the current stream and writes the bytes to
  129. // the destination stream until all bytes are read, starting at
  130. // the current position.
  131. public void CopyTo(Stream destination)
  132. {
  133. int bufferSize = GetCopyBufferSize();
  134. CopyTo(destination, bufferSize);
  135. }
  136. public virtual void CopyTo(Stream destination, int bufferSize)
  137. {
  138. StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
  139. byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
  140. try
  141. {
  142. int read;
  143. while ((read = Read(buffer, 0, buffer.Length)) != 0)
  144. {
  145. destination.Write(buffer, 0, read);
  146. }
  147. }
  148. finally
  149. {
  150. ArrayPool<byte>.Shared.Return(buffer);
  151. }
  152. }
  153. private int GetCopyBufferSize()
  154. {
  155. int bufferSize = DefaultCopyBufferSize;
  156. if (CanSeek)
  157. {
  158. long length = Length;
  159. long position = Position;
  160. if (length <= position) // Handles negative overflows
  161. {
  162. // There are no bytes left in the stream to copy.
  163. // However, because CopyTo{Async} is virtual, we need to
  164. // ensure that any override is still invoked to provide its
  165. // own validation, so we use the smallest legal buffer size here.
  166. bufferSize = 1;
  167. }
  168. else
  169. {
  170. long remaining = length - position;
  171. if (remaining > 0)
  172. {
  173. // In the case of a positive overflow, stick to the default size
  174. bufferSize = (int)Math.Min(bufferSize, remaining);
  175. }
  176. }
  177. }
  178. return bufferSize;
  179. }
  180. // Stream used to require that all cleanup logic went into Close(),
  181. // which was thought up before we invented IDisposable. However, we
  182. // need to follow the IDisposable pattern so that users can write
  183. // sensible subclasses without needing to inspect all their base
  184. // classes, and without worrying about version brittleness, from a
  185. // base class switching to the Dispose pattern. We're moving
  186. // Stream to the Dispose(bool) pattern - that's where all subclasses
  187. // should put their cleanup now.
  188. public virtual void Close()
  189. {
  190. Dispose(true);
  191. GC.SuppressFinalize(this);
  192. }
  193. public void Dispose()
  194. {
  195. Close();
  196. }
  197. protected virtual void Dispose(bool disposing)
  198. {
  199. // Note: Never change this to call other virtual methods on Stream
  200. // like Write, since the state on subclasses has already been
  201. // torn down. This is the last code to run on cleanup for a stream.
  202. }
  203. public virtual ValueTask DisposeAsync()
  204. {
  205. try
  206. {
  207. Dispose();
  208. return default;
  209. }
  210. catch (Exception exc)
  211. {
  212. return new ValueTask(Task.FromException(exc));
  213. }
  214. }
  215. public abstract void Flush();
  216. public Task FlushAsync()
  217. {
  218. return FlushAsync(CancellationToken.None);
  219. }
  220. public virtual Task FlushAsync(CancellationToken cancellationToken)
  221. {
  222. return Task.Factory.StartNew(state => ((Stream)state).Flush(), this,
  223. cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  224. }
  225. [Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")]
  226. protected virtual WaitHandle CreateWaitHandle()
  227. {
  228. return new ManualResetEvent(false);
  229. }
  230. public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  231. {
  232. return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
  233. }
  234. internal IAsyncResult BeginReadInternal(
  235. byte[] buffer, int offset, int count, AsyncCallback callback, object state,
  236. bool serializeAsynchronously, bool apm)
  237. {
  238. if (!CanRead) throw Error.GetReadNotSupported();
  239. // To avoid a race with a stream's position pointer & generating race conditions
  240. // with internal buffer indexes in our own streams that
  241. // don't natively support async IO operations when there are multiple
  242. // async requests outstanding, we will block the application's main
  243. // thread if it does a second IO request until the first one completes.
  244. var semaphore = EnsureAsyncActiveSemaphoreInitialized();
  245. Task semaphoreTask = null;
  246. if (serializeAsynchronously)
  247. {
  248. semaphoreTask = semaphore.WaitAsync();
  249. }
  250. else
  251. {
  252. semaphore.Wait();
  253. }
  254. // Create the task to asynchronously do a Read. This task serves both
  255. // as the asynchronous work item and as the IAsyncResult returned to the user.
  256. var asyncResult = new ReadWriteTask(true /*isRead*/, apm, delegate
  257. {
  258. // The ReadWriteTask stores all of the parameters to pass to Read.
  259. // As we're currently inside of it, we can get the current task
  260. // and grab the parameters from it.
  261. var thisTask = Task.InternalCurrent as ReadWriteTask;
  262. Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
  263. try
  264. {
  265. // Do the Read and return the number of bytes read
  266. return thisTask._stream.Read(thisTask._buffer, thisTask._offset, thisTask._count);
  267. }
  268. finally
  269. {
  270. // If this implementation is part of Begin/EndXx, then the EndXx method will handle
  271. // finishing the async operation. However, if this is part of XxAsync, then there won't
  272. // be an end method, and this task is responsible for cleaning up.
  273. if (!thisTask._apm)
  274. {
  275. thisTask._stream.FinishTrackingAsyncOperation();
  276. }
  277. thisTask.ClearBeginState(); // just to help alleviate some memory pressure
  278. }
  279. }, state, this, buffer, offset, count, callback);
  280. // Schedule it
  281. if (semaphoreTask != null)
  282. RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
  283. else
  284. RunReadWriteTask(asyncResult);
  285. return asyncResult; // return it
  286. }
  287. public virtual int EndRead(IAsyncResult asyncResult)
  288. {
  289. if (asyncResult == null)
  290. throw new ArgumentNullException(nameof(asyncResult));
  291. var readTask = _activeReadWriteTask;
  292. if (readTask == null)
  293. {
  294. throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
  295. }
  296. else if (readTask != asyncResult)
  297. {
  298. throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
  299. }
  300. else if (!readTask._isRead)
  301. {
  302. throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
  303. }
  304. try
  305. {
  306. return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception
  307. }
  308. finally
  309. {
  310. FinishTrackingAsyncOperation();
  311. }
  312. }
  313. public Task<int> ReadAsync(byte[] buffer, int offset, int count)
  314. {
  315. return ReadAsync(buffer, offset, count, CancellationToken.None);
  316. }
  317. public virtual Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  318. {
  319. // If cancellation was requested, bail early with an already completed task.
  320. // Otherwise, return a task that represents the Begin/End methods.
  321. return cancellationToken.IsCancellationRequested
  322. ? Task.FromCanceled<int>(cancellationToken)
  323. : BeginEndReadAsync(buffer, offset, count);
  324. }
  325. public virtual ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
  326. {
  327. if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> array))
  328. {
  329. return new ValueTask<int>(ReadAsync(array.Array, array.Offset, array.Count, cancellationToken));
  330. }
  331. else
  332. {
  333. byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
  334. return FinishReadAsync(ReadAsync(sharedBuffer, 0, buffer.Length, cancellationToken), sharedBuffer, buffer);
  335. async ValueTask<int> FinishReadAsync(Task<int> readTask, byte[] localBuffer, Memory<byte> localDestination)
  336. {
  337. try
  338. {
  339. int result = await readTask.ConfigureAwait(false);
  340. new Span<byte>(localBuffer, 0, result).CopyTo(localDestination.Span);
  341. return result;
  342. }
  343. finally
  344. {
  345. ArrayPool<byte>.Shared.Return(localBuffer);
  346. }
  347. }
  348. }
  349. }
  350. private Task<int> BeginEndReadAsync(byte[] buffer, int offset, int count)
  351. {
  352. if (!HasOverriddenBeginEndRead())
  353. {
  354. // If the Stream does not override Begin/EndRead, then we can take an optimized path
  355. // that skips an extra layer of tasks / IAsyncResults.
  356. return (Task<int>)BeginReadInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
  357. }
  358. // Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
  359. return TaskFactory<int>.FromAsyncTrim(
  360. this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count },
  361. (stream, args, callback, state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
  362. (stream, asyncResult) => stream.EndRead(asyncResult)); // cached by compiler
  363. }
  364. private struct ReadWriteParameters // struct for arguments to Read and Write calls
  365. {
  366. internal byte[] Buffer;
  367. internal int Offset;
  368. internal int Count;
  369. }
  370. public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  371. {
  372. return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
  373. }
  374. internal IAsyncResult BeginWriteInternal(
  375. byte[] buffer, int offset, int count, AsyncCallback callback, object state,
  376. bool serializeAsynchronously, bool apm)
  377. {
  378. if (!CanWrite) throw Error.GetWriteNotSupported();
  379. // To avoid a race condition with a stream's position pointer & generating conditions
  380. // with internal buffer indexes in our own streams that
  381. // don't natively support async IO operations when there are multiple
  382. // async requests outstanding, we will block the application's main
  383. // thread if it does a second IO request until the first one completes.
  384. var semaphore = EnsureAsyncActiveSemaphoreInitialized();
  385. Task semaphoreTask = null;
  386. if (serializeAsynchronously)
  387. {
  388. semaphoreTask = semaphore.WaitAsync(); // kick off the asynchronous wait, but don't block
  389. }
  390. else
  391. {
  392. semaphore.Wait(); // synchronously wait here
  393. }
  394. // Create the task to asynchronously do a Write. This task serves both
  395. // as the asynchronous work item and as the IAsyncResult returned to the user.
  396. var asyncResult = new ReadWriteTask(false /*isRead*/, apm, delegate
  397. {
  398. // The ReadWriteTask stores all of the parameters to pass to Write.
  399. // As we're currently inside of it, we can get the current task
  400. // and grab the parameters from it.
  401. var thisTask = Task.InternalCurrent as ReadWriteTask;
  402. Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
  403. try
  404. {
  405. // Do the Write
  406. thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count);
  407. return 0; // not used, but signature requires a value be returned
  408. }
  409. finally
  410. {
  411. // If this implementation is part of Begin/EndXx, then the EndXx method will handle
  412. // finishing the async operation. However, if this is part of XxAsync, then there won't
  413. // be an end method, and this task is responsible for cleaning up.
  414. if (!thisTask._apm)
  415. {
  416. thisTask._stream.FinishTrackingAsyncOperation();
  417. }
  418. thisTask.ClearBeginState(); // just to help alleviate some memory pressure
  419. }
  420. }, state, this, buffer, offset, count, callback);
  421. // Schedule it
  422. if (semaphoreTask != null)
  423. RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
  424. else
  425. RunReadWriteTask(asyncResult);
  426. return asyncResult; // return it
  427. }
  428. private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask)
  429. {
  430. Debug.Assert(readWriteTask != null);
  431. Debug.Assert(asyncWaiter != null);
  432. // If the wait has already completed, run the task.
  433. if (asyncWaiter.IsCompleted)
  434. {
  435. Debug.Assert(asyncWaiter.IsCompletedSuccessfully, "The semaphore wait should always complete successfully.");
  436. RunReadWriteTask(readWriteTask);
  437. }
  438. else // Otherwise, wait for our turn, and then run the task.
  439. {
  440. asyncWaiter.ContinueWith((t, state) =>
  441. {
  442. Debug.Assert(t.IsCompletedSuccessfully, "The semaphore wait should always complete successfully.");
  443. var rwt = (ReadWriteTask)state;
  444. rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask);
  445. }, readWriteTask, default, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
  446. }
  447. }
  448. private void RunReadWriteTask(ReadWriteTask readWriteTask)
  449. {
  450. Debug.Assert(readWriteTask != null);
  451. Debug.Assert(_activeReadWriteTask == null, "Expected no other readers or writers");
  452. // Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race.
  453. // Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding
  454. // two interlocked operations. However, if ReadWriteTask is ever changed to use
  455. // a cancellation token, this should be changed to use Start.
  456. _activeReadWriteTask = readWriteTask; // store the task so that EndXx can validate it's given the right one
  457. readWriteTask.m_taskScheduler = TaskScheduler.Default;
  458. readWriteTask.ScheduleAndStart(needsProtection: false);
  459. }
  460. private void FinishTrackingAsyncOperation()
  461. {
  462. _activeReadWriteTask = null;
  463. Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
  464. _asyncActiveSemaphore.Release();
  465. }
  466. public virtual void EndWrite(IAsyncResult asyncResult)
  467. {
  468. if (asyncResult == null)
  469. throw new ArgumentNullException(nameof(asyncResult));
  470. var writeTask = _activeReadWriteTask;
  471. if (writeTask == null)
  472. {
  473. throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
  474. }
  475. else if (writeTask != asyncResult)
  476. {
  477. throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
  478. }
  479. else if (writeTask._isRead)
  480. {
  481. throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
  482. }
  483. try
  484. {
  485. writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions
  486. Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion);
  487. }
  488. finally
  489. {
  490. FinishTrackingAsyncOperation();
  491. }
  492. }
  493. // Task used by BeginRead / BeginWrite to do Read / Write asynchronously.
  494. // A single instance of this task serves four purposes:
  495. // 1. The work item scheduled to run the Read / Write operation
  496. // 2. The state holding the arguments to be passed to Read / Write
  497. // 3. The IAsyncResult returned from BeginRead / BeginWrite
  498. // 4. The completion action that runs to invoke the user-provided callback.
  499. // This last item is a bit tricky. Before the AsyncCallback is invoked, the
  500. // IAsyncResult must have completed, so we can't just invoke the handler
  501. // from within the task, since it is the IAsyncResult, and thus it's not
  502. // yet completed. Instead, we use AddCompletionAction to install this
  503. // task as its own completion handler. That saves the need to allocate
  504. // a separate completion handler, it guarantees that the task will
  505. // have completed by the time the handler is invoked, and it allows
  506. // the handler to be invoked synchronously upon the completion of the
  507. // task. This all enables BeginRead / BeginWrite to be implemented
  508. // with a single allocation.
  509. private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction
  510. {
  511. internal readonly bool _isRead;
  512. internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync
  513. internal Stream _stream;
  514. internal byte[] _buffer;
  515. internal readonly int _offset;
  516. internal readonly int _count;
  517. private AsyncCallback _callback;
  518. private ExecutionContext _context;
  519. internal void ClearBeginState() // Used to allow the args to Read/Write to be made available for GC
  520. {
  521. _stream = null;
  522. _buffer = null;
  523. }
  524. public ReadWriteTask(
  525. bool isRead,
  526. bool apm,
  527. Func<object, int> function, object state,
  528. Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback) :
  529. base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach)
  530. {
  531. Debug.Assert(function != null);
  532. Debug.Assert(stream != null);
  533. Debug.Assert(buffer != null);
  534. // Store the arguments
  535. _isRead = isRead;
  536. _apm = apm;
  537. _stream = stream;
  538. _buffer = buffer;
  539. _offset = offset;
  540. _count = count;
  541. // If a callback was provided, we need to:
  542. // - Store the user-provided handler
  543. // - Capture an ExecutionContext under which to invoke the handler
  544. // - Add this task as its own completion handler so that the Invoke method
  545. // will run the callback when this task completes.
  546. if (callback != null)
  547. {
  548. _callback = callback;
  549. _context = ExecutionContext.Capture();
  550. base.AddCompletionAction(this);
  551. }
  552. }
  553. private static void InvokeAsyncCallback(object completedTask)
  554. {
  555. var rwc = (ReadWriteTask)completedTask;
  556. var callback = rwc._callback;
  557. rwc._callback = null;
  558. callback(rwc);
  559. }
  560. private static ContextCallback s_invokeAsyncCallback;
  561. void ITaskCompletionAction.Invoke(Task completingTask)
  562. {
  563. // Get the ExecutionContext. If there is none, just run the callback
  564. // directly, passing in the completed task as the IAsyncResult.
  565. // If there is one, process it with ExecutionContext.Run.
  566. var context = _context;
  567. if (context == null)
  568. {
  569. var callback = _callback;
  570. _callback = null;
  571. callback(completingTask);
  572. }
  573. else
  574. {
  575. _context = null;
  576. var invokeAsyncCallback = s_invokeAsyncCallback;
  577. if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign race condition
  578. ExecutionContext.RunInternal(context, invokeAsyncCallback, this);
  579. }
  580. }
  581. bool ITaskCompletionAction.InvokeMayRunArbitraryCode { get { return true; } }
  582. }
  583. public Task WriteAsync(byte[] buffer, int offset, int count)
  584. {
  585. return WriteAsync(buffer, offset, count, CancellationToken.None);
  586. }
  587. public virtual Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  588. {
  589. // If cancellation was requested, bail early with an already completed task.
  590. // Otherwise, return a task that represents the Begin/End methods.
  591. return cancellationToken.IsCancellationRequested
  592. ? Task.FromCanceled(cancellationToken)
  593. : BeginEndWriteAsync(buffer, offset, count);
  594. }
  595. public virtual ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
  596. {
  597. if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> array))
  598. {
  599. return new ValueTask(WriteAsync(array.Array, array.Offset, array.Count, cancellationToken));
  600. }
  601. else
  602. {
  603. byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
  604. buffer.Span.CopyTo(sharedBuffer);
  605. return new ValueTask(FinishWriteAsync(WriteAsync(sharedBuffer, 0, buffer.Length, cancellationToken), sharedBuffer));
  606. }
  607. }
  608. private async Task FinishWriteAsync(Task writeTask, byte[] localBuffer)
  609. {
  610. try
  611. {
  612. await writeTask.ConfigureAwait(false);
  613. }
  614. finally
  615. {
  616. ArrayPool<byte>.Shared.Return(localBuffer);
  617. }
  618. }
  619. private Task BeginEndWriteAsync(byte[] buffer, int offset, int count)
  620. {
  621. if (!HasOverriddenBeginEndWrite())
  622. {
  623. // If the Stream does not override Begin/EndWrite, then we can take an optimized path
  624. // that skips an extra layer of tasks / IAsyncResults.
  625. return (Task)BeginWriteInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
  626. }
  627. // Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
  628. return TaskFactory<VoidTaskResult>.FromAsyncTrim(
  629. this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count },
  630. (stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
  631. (stream, asyncResult) => // cached by compiler
  632. {
  633. stream.EndWrite(asyncResult);
  634. return default;
  635. });
  636. }
  637. public abstract long Seek(long offset, SeekOrigin origin);
  638. public abstract void SetLength(long value);
  639. public abstract int Read(byte[] buffer, int offset, int count);
  640. public virtual int Read(Span<byte> buffer)
  641. {
  642. byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
  643. try
  644. {
  645. int numRead = Read(sharedBuffer, 0, buffer.Length);
  646. if ((uint)numRead > (uint)buffer.Length)
  647. {
  648. throw new IOException(SR.IO_StreamTooLong);
  649. }
  650. new Span<byte>(sharedBuffer, 0, numRead).CopyTo(buffer);
  651. return numRead;
  652. }
  653. finally { ArrayPool<byte>.Shared.Return(sharedBuffer); }
  654. }
  655. // Reads one byte from the stream by calling Read(byte[], int, int).
  656. // Will return an unsigned byte cast to an int or -1 on end of stream.
  657. // This implementation does not perform well because it allocates a new
  658. // byte[] each time you call it, and should be overridden by any
  659. // subclass that maintains an internal buffer. Then, it can help perf
  660. // significantly for people who are reading one byte at a time.
  661. public virtual int ReadByte()
  662. {
  663. byte[] oneByteArray = new byte[1];
  664. int r = Read(oneByteArray, 0, 1);
  665. if (r == 0)
  666. return -1;
  667. return oneByteArray[0];
  668. }
  669. public abstract void Write(byte[] buffer, int offset, int count);
  670. public virtual void Write(ReadOnlySpan<byte> buffer)
  671. {
  672. byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
  673. try
  674. {
  675. buffer.CopyTo(sharedBuffer);
  676. Write(sharedBuffer, 0, buffer.Length);
  677. }
  678. finally { ArrayPool<byte>.Shared.Return(sharedBuffer); }
  679. }
  680. // Writes one byte from the stream by calling Write(byte[], int, int).
  681. // This implementation does not perform well because it allocates a new
  682. // byte[] each time you call it, and should be overridden by any
  683. // subclass that maintains an internal buffer. Then, it can help perf
  684. // significantly for people who are writing one byte at a time.
  685. public virtual void WriteByte(byte value)
  686. {
  687. byte[] oneByteArray = new byte[1];
  688. oneByteArray[0] = value;
  689. Write(oneByteArray, 0, 1);
  690. }
  691. public static Stream Synchronized(Stream stream)
  692. {
  693. if (stream == null)
  694. throw new ArgumentNullException(nameof(stream));
  695. if (stream is SyncStream)
  696. return stream;
  697. return new SyncStream(stream);
  698. }
  699. [Obsolete("Do not call or override this method.")]
  700. protected virtual void ObjectInvariant()
  701. {
  702. }
  703. internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  704. {
  705. // To avoid a race with a stream's position pointer & generating conditions
  706. // with internal buffer indexes in our own streams that
  707. // don't natively support async IO operations when there are multiple
  708. // async requests outstanding, we will block the application's main
  709. // thread and do the IO synchronously.
  710. // This can't perform well - use a different approach.
  711. SynchronousAsyncResult asyncResult;
  712. try
  713. {
  714. int numRead = Read(buffer, offset, count);
  715. asyncResult = new SynchronousAsyncResult(numRead, state);
  716. }
  717. catch (IOException ex)
  718. {
  719. asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false);
  720. }
  721. if (callback != null)
  722. {
  723. callback(asyncResult);
  724. }
  725. return asyncResult;
  726. }
  727. internal static int BlockingEndRead(IAsyncResult asyncResult)
  728. {
  729. return SynchronousAsyncResult.EndRead(asyncResult);
  730. }
  731. internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  732. {
  733. // To avoid a race condition with a stream's position pointer & generating conditions
  734. // with internal buffer indexes in our own streams that
  735. // don't natively support async IO operations when there are multiple
  736. // async requests outstanding, we will block the application's main
  737. // thread and do the IO synchronously.
  738. // This can't perform well - use a different approach.
  739. SynchronousAsyncResult asyncResult;
  740. try
  741. {
  742. Write(buffer, offset, count);
  743. asyncResult = new SynchronousAsyncResult(state);
  744. }
  745. catch (IOException ex)
  746. {
  747. asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true);
  748. }
  749. if (callback != null)
  750. {
  751. callback(asyncResult);
  752. }
  753. return asyncResult;
  754. }
  755. internal static void BlockingEndWrite(IAsyncResult asyncResult)
  756. {
  757. SynchronousAsyncResult.EndWrite(asyncResult);
  758. }
  759. private sealed class NullStream : Stream
  760. {
  761. private static readonly Task<int> s_zeroTask = Task.FromResult(0);
  762. internal NullStream() { }
  763. public override bool CanRead => true;
  764. public override bool CanWrite => true;
  765. public override bool CanSeek => true;
  766. public override long Length => 0;
  767. public override long Position
  768. {
  769. get { return 0; }
  770. set { }
  771. }
  772. public override void CopyTo(Stream destination, int bufferSize)
  773. {
  774. StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
  775. // After we validate arguments this is a nop.
  776. }
  777. public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
  778. {
  779. // Validate arguments here for compat, since previously this method
  780. // was inherited from Stream (which did check its arguments).
  781. StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
  782. return cancellationToken.IsCancellationRequested ?
  783. Task.FromCanceled(cancellationToken) :
  784. Task.CompletedTask;
  785. }
  786. protected override void Dispose(bool disposing)
  787. {
  788. // Do nothing - we don't want NullStream singleton (static) to be closable
  789. }
  790. public override void Flush()
  791. {
  792. }
  793. public override Task FlushAsync(CancellationToken cancellationToken)
  794. {
  795. return cancellationToken.IsCancellationRequested ?
  796. Task.FromCanceled(cancellationToken) :
  797. Task.CompletedTask;
  798. }
  799. public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  800. {
  801. if (!CanRead) throw Error.GetReadNotSupported();
  802. return BlockingBeginRead(buffer, offset, count, callback, state);
  803. }
  804. public override int EndRead(IAsyncResult asyncResult)
  805. {
  806. if (asyncResult == null)
  807. throw new ArgumentNullException(nameof(asyncResult));
  808. return BlockingEndRead(asyncResult);
  809. }
  810. public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  811. {
  812. if (!CanWrite) throw Error.GetWriteNotSupported();
  813. return BlockingBeginWrite(buffer, offset, count, callback, state);
  814. }
  815. public override void EndWrite(IAsyncResult asyncResult)
  816. {
  817. if (asyncResult == null)
  818. throw new ArgumentNullException(nameof(asyncResult));
  819. BlockingEndWrite(asyncResult);
  820. }
  821. public override int Read(byte[] buffer, int offset, int count)
  822. {
  823. return 0;
  824. }
  825. public override int Read(Span<byte> buffer)
  826. {
  827. return 0;
  828. }
  829. public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  830. {
  831. return s_zeroTask;
  832. }
  833. public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
  834. {
  835. return new ValueTask<int>(0);
  836. }
  837. public override int ReadByte()
  838. {
  839. return -1;
  840. }
  841. public override void Write(byte[] buffer, int offset, int count)
  842. {
  843. }
  844. public override void Write(ReadOnlySpan<byte> buffer)
  845. {
  846. }
  847. public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  848. {
  849. return cancellationToken.IsCancellationRequested ?
  850. Task.FromCanceled(cancellationToken) :
  851. Task.CompletedTask;
  852. }
  853. public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
  854. {
  855. return cancellationToken.IsCancellationRequested ?
  856. new ValueTask(Task.FromCanceled(cancellationToken)) :
  857. default;
  858. }
  859. public override void WriteByte(byte value)
  860. {
  861. }
  862. public override long Seek(long offset, SeekOrigin origin)
  863. {
  864. return 0;
  865. }
  866. public override void SetLength(long length)
  867. {
  868. }
  869. }
  870. /// <summary>Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class.</summary>
  871. private sealed class SynchronousAsyncResult : IAsyncResult
  872. {
  873. private readonly object _stateObject;
  874. private readonly bool _isWrite;
  875. private ManualResetEvent _waitHandle;
  876. private ExceptionDispatchInfo _exceptionInfo;
  877. private bool _endXxxCalled;
  878. private int _bytesRead;
  879. internal SynchronousAsyncResult(int bytesRead, object asyncStateObject)
  880. {
  881. _bytesRead = bytesRead;
  882. _stateObject = asyncStateObject;
  883. //_isWrite = false;
  884. }
  885. internal SynchronousAsyncResult(object asyncStateObject)
  886. {
  887. _stateObject = asyncStateObject;
  888. _isWrite = true;
  889. }
  890. internal SynchronousAsyncResult(Exception ex, object asyncStateObject, bool isWrite)
  891. {
  892. _exceptionInfo = ExceptionDispatchInfo.Capture(ex);
  893. _stateObject = asyncStateObject;
  894. _isWrite = isWrite;
  895. }
  896. public bool IsCompleted
  897. {
  898. // We never hand out objects of this type to the user before the synchronous IO completed:
  899. get { return true; }
  900. }
  901. public WaitHandle AsyncWaitHandle
  902. {
  903. get
  904. {
  905. return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true));
  906. }
  907. }
  908. public object AsyncState
  909. {
  910. get { return _stateObject; }
  911. }
  912. public bool CompletedSynchronously
  913. {
  914. get { return true; }
  915. }
  916. internal void ThrowIfError()
  917. {
  918. if (_exceptionInfo != null)
  919. _exceptionInfo.Throw();
  920. }
  921. internal static int EndRead(IAsyncResult asyncResult)
  922. {
  923. SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
  924. if (ar == null || ar._isWrite)
  925. throw new ArgumentException(SR.Arg_WrongAsyncResult);
  926. if (ar._endXxxCalled)
  927. throw new ArgumentException(SR.InvalidOperation_EndReadCalledMultiple);
  928. ar._endXxxCalled = true;
  929. ar.ThrowIfError();
  930. return ar._bytesRead;
  931. }
  932. internal static void EndWrite(IAsyncResult asyncResult)
  933. {
  934. SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
  935. if (ar == null || !ar._isWrite)
  936. throw new ArgumentException(SR.Arg_WrongAsyncResult);
  937. if (ar._endXxxCalled)
  938. throw new ArgumentException(SR.InvalidOperation_EndWriteCalledMultiple);
  939. ar._endXxxCalled = true;
  940. ar.ThrowIfError();
  941. }
  942. } // class SynchronousAsyncResult
  943. // SyncStream is a wrapper around a stream that takes
  944. // a lock for every operation making it thread safe.
  945. private sealed class SyncStream : Stream, IDisposable
  946. {
  947. private Stream _stream;
  948. internal SyncStream(Stream stream)
  949. {
  950. if (stream == null)
  951. throw new ArgumentNullException(nameof(stream));
  952. _stream = stream;
  953. }
  954. public override bool CanRead => _stream.CanRead;
  955. public override bool CanWrite => _stream.CanWrite;
  956. public override bool CanSeek => _stream.CanSeek;
  957. public override bool CanTimeout => _stream.CanTimeout;
  958. public override long Length
  959. {
  960. get
  961. {
  962. lock (_stream)
  963. {
  964. return _stream.Length;
  965. }
  966. }
  967. }
  968. public override long Position
  969. {
  970. get
  971. {
  972. lock (_stream)
  973. {
  974. return _stream.Position;
  975. }
  976. }
  977. set
  978. {
  979. lock (_stream)
  980. {
  981. _stream.Position = value;
  982. }
  983. }
  984. }
  985. public override int ReadTimeout
  986. {
  987. get
  988. {
  989. return _stream.ReadTimeout;
  990. }
  991. set
  992. {
  993. _stream.ReadTimeout = value;
  994. }
  995. }
  996. public override int WriteTimeout
  997. {
  998. get
  999. {
  1000. return _stream.WriteTimeout;
  1001. }
  1002. set
  1003. {
  1004. _stream.WriteTimeout = value;
  1005. }
  1006. }
  1007. // In the off chance that some wrapped stream has different
  1008. // semantics for Close vs. Dispose, let's preserve that.
  1009. public override void Close()
  1010. {
  1011. lock (_stream)
  1012. {
  1013. try
  1014. {
  1015. _stream.Close();
  1016. }
  1017. finally
  1018. {
  1019. base.Dispose(true);
  1020. }
  1021. }
  1022. }
  1023. protected override void Dispose(bool disposing)
  1024. {
  1025. lock (_stream)
  1026. {
  1027. try
  1028. {
  1029. // Explicitly pick up a potentially methodimpl'ed Dispose
  1030. if (disposing)
  1031. ((IDisposable)_stream).Dispose();
  1032. }
  1033. finally
  1034. {
  1035. base.Dispose(disposing);
  1036. }
  1037. }
  1038. }
  1039. public override ValueTask DisposeAsync()
  1040. {
  1041. lock (_stream)
  1042. return _stream.DisposeAsync();
  1043. }
  1044. public override void Flush()
  1045. {
  1046. lock (_stream)
  1047. _stream.Flush();
  1048. }
  1049. public override int Read(byte[] bytes, int offset, int count)
  1050. {
  1051. lock (_stream)
  1052. return _stream.Read(bytes, offset, count);
  1053. }
  1054. public override int Read(Span<byte> buffer)
  1055. {
  1056. lock (_stream)
  1057. return _stream.Read(buffer);
  1058. }
  1059. public override int ReadByte()
  1060. {
  1061. lock (_stream)
  1062. return _stream.ReadByte();
  1063. }
  1064. public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  1065. {
  1066. #if CORERT
  1067. throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251
  1068. #else
  1069. bool overridesBeginRead = _stream.HasOverriddenBeginEndRead();
  1070. lock (_stream)
  1071. {
  1072. // If the Stream does have its own BeginRead implementation, then we must use that override.
  1073. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
  1074. // which ensures only one asynchronous operation does so with an asynchronous wait rather
  1075. // than a synchronous wait. A synchronous wait will result in a deadlock condition, because
  1076. // the EndXx method for the outstanding async operation won't be able to acquire the lock on
  1077. // _stream due to this call blocked while holding the lock.
  1078. return overridesBeginRead ?
  1079. _stream.BeginRead(buffer, offset, count, callback, state) :
  1080. _stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
  1081. }
  1082. #endif
  1083. }
  1084. public override int EndRead(IAsyncResult asyncResult)
  1085. {
  1086. if (asyncResult == null)
  1087. throw new ArgumentNullException(nameof(asyncResult));
  1088. lock (_stream)
  1089. return _stream.EndRead(asyncResult);
  1090. }
  1091. public override long Seek(long offset, SeekOrigin origin)
  1092. {
  1093. lock (_stream)
  1094. return _stream.Seek(offset, origin);
  1095. }
  1096. public override void SetLength(long length)
  1097. {
  1098. lock (_stream)
  1099. _stream.SetLength(length);
  1100. }
  1101. public override void Write(byte[] bytes, int offset, int count)
  1102. {
  1103. lock (_stream)
  1104. _stream.Write(bytes, offset, count);
  1105. }
  1106. public override void Write(ReadOnlySpan<byte> buffer)
  1107. {
  1108. lock (_stream)
  1109. _stream.Write(buffer);
  1110. }
  1111. public override void WriteByte(byte b)
  1112. {
  1113. lock (_stream)
  1114. _stream.WriteByte(b);
  1115. }
  1116. public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  1117. {
  1118. #if CORERT
  1119. throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251
  1120. #else
  1121. bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite();
  1122. lock (_stream)
  1123. {
  1124. // If the Stream does have its own BeginWrite implementation, then we must use that override.
  1125. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
  1126. // which ensures only one asynchronous operation does so with an asynchronous wait rather
  1127. // than a synchronous wait. A synchronous wait will result in a deadlock condition, because
  1128. // the EndXx method for the outstanding async operation won't be able to acquire the lock on
  1129. // _stream due to this call blocked while holding the lock.
  1130. return overridesBeginWrite ?
  1131. _stream.BeginWrite(buffer, offset, count, callback, state) :
  1132. _stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
  1133. }
  1134. #endif
  1135. }
  1136. public override void EndWrite(IAsyncResult asyncResult)
  1137. {
  1138. if (asyncResult == null)
  1139. throw new ArgumentNullException(nameof(asyncResult));
  1140. lock (_stream)
  1141. _stream.EndWrite(asyncResult);
  1142. }
  1143. }
  1144. }
  1145. }