Stream.cs 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339
  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. if (!(asyncResult is SynchronousAsyncResult ar) || ar._isWrite)
  924. throw new ArgumentException(SR.Arg_WrongAsyncResult);
  925. if (ar._endXxxCalled)
  926. throw new ArgumentException(SR.InvalidOperation_EndReadCalledMultiple);
  927. ar._endXxxCalled = true;
  928. ar.ThrowIfError();
  929. return ar._bytesRead;
  930. }
  931. internal static void EndWrite(IAsyncResult asyncResult)
  932. {
  933. if (!(asyncResult is SynchronousAsyncResult ar) || !ar._isWrite)
  934. throw new ArgumentException(SR.Arg_WrongAsyncResult);
  935. if (ar._endXxxCalled)
  936. throw new ArgumentException(SR.InvalidOperation_EndWriteCalledMultiple);
  937. ar._endXxxCalled = true;
  938. ar.ThrowIfError();
  939. }
  940. } // class SynchronousAsyncResult
  941. // SyncStream is a wrapper around a stream that takes
  942. // a lock for every operation making it thread safe.
  943. private sealed class SyncStream : Stream, IDisposable
  944. {
  945. private Stream _stream;
  946. internal SyncStream(Stream stream)
  947. {
  948. if (stream == null)
  949. throw new ArgumentNullException(nameof(stream));
  950. _stream = stream;
  951. }
  952. public override bool CanRead => _stream.CanRead;
  953. public override bool CanWrite => _stream.CanWrite;
  954. public override bool CanSeek => _stream.CanSeek;
  955. public override bool CanTimeout => _stream.CanTimeout;
  956. public override long Length
  957. {
  958. get
  959. {
  960. lock (_stream)
  961. {
  962. return _stream.Length;
  963. }
  964. }
  965. }
  966. public override long Position
  967. {
  968. get
  969. {
  970. lock (_stream)
  971. {
  972. return _stream.Position;
  973. }
  974. }
  975. set
  976. {
  977. lock (_stream)
  978. {
  979. _stream.Position = value;
  980. }
  981. }
  982. }
  983. public override int ReadTimeout
  984. {
  985. get
  986. {
  987. return _stream.ReadTimeout;
  988. }
  989. set
  990. {
  991. _stream.ReadTimeout = value;
  992. }
  993. }
  994. public override int WriteTimeout
  995. {
  996. get
  997. {
  998. return _stream.WriteTimeout;
  999. }
  1000. set
  1001. {
  1002. _stream.WriteTimeout = value;
  1003. }
  1004. }
  1005. // In the off chance that some wrapped stream has different
  1006. // semantics for Close vs. Dispose, let's preserve that.
  1007. public override void Close()
  1008. {
  1009. lock (_stream)
  1010. {
  1011. try
  1012. {
  1013. _stream.Close();
  1014. }
  1015. finally
  1016. {
  1017. base.Dispose(true);
  1018. }
  1019. }
  1020. }
  1021. protected override void Dispose(bool disposing)
  1022. {
  1023. lock (_stream)
  1024. {
  1025. try
  1026. {
  1027. // Explicitly pick up a potentially methodimpl'ed Dispose
  1028. if (disposing)
  1029. ((IDisposable)_stream).Dispose();
  1030. }
  1031. finally
  1032. {
  1033. base.Dispose(disposing);
  1034. }
  1035. }
  1036. }
  1037. public override ValueTask DisposeAsync()
  1038. {
  1039. lock (_stream)
  1040. return _stream.DisposeAsync();
  1041. }
  1042. public override void Flush()
  1043. {
  1044. lock (_stream)
  1045. _stream.Flush();
  1046. }
  1047. public override int Read(byte[] bytes, int offset, int count)
  1048. {
  1049. lock (_stream)
  1050. return _stream.Read(bytes, offset, count);
  1051. }
  1052. public override int Read(Span<byte> buffer)
  1053. {
  1054. lock (_stream)
  1055. return _stream.Read(buffer);
  1056. }
  1057. public override int ReadByte()
  1058. {
  1059. lock (_stream)
  1060. return _stream.ReadByte();
  1061. }
  1062. public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  1063. {
  1064. #if CORERT
  1065. throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251
  1066. #else
  1067. bool overridesBeginRead = _stream.HasOverriddenBeginEndRead();
  1068. lock (_stream)
  1069. {
  1070. // If the Stream does have its own BeginRead implementation, then we must use that override.
  1071. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
  1072. // which ensures only one asynchronous operation does so with an asynchronous wait rather
  1073. // than a synchronous wait. A synchronous wait will result in a deadlock condition, because
  1074. // the EndXx method for the outstanding async operation won't be able to acquire the lock on
  1075. // _stream due to this call blocked while holding the lock.
  1076. return overridesBeginRead ?
  1077. _stream.BeginRead(buffer, offset, count, callback, state) :
  1078. _stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
  1079. }
  1080. #endif
  1081. }
  1082. public override int EndRead(IAsyncResult asyncResult)
  1083. {
  1084. if (asyncResult == null)
  1085. throw new ArgumentNullException(nameof(asyncResult));
  1086. lock (_stream)
  1087. return _stream.EndRead(asyncResult);
  1088. }
  1089. public override long Seek(long offset, SeekOrigin origin)
  1090. {
  1091. lock (_stream)
  1092. return _stream.Seek(offset, origin);
  1093. }
  1094. public override void SetLength(long length)
  1095. {
  1096. lock (_stream)
  1097. _stream.SetLength(length);
  1098. }
  1099. public override void Write(byte[] bytes, int offset, int count)
  1100. {
  1101. lock (_stream)
  1102. _stream.Write(bytes, offset, count);
  1103. }
  1104. public override void Write(ReadOnlySpan<byte> buffer)
  1105. {
  1106. lock (_stream)
  1107. _stream.Write(buffer);
  1108. }
  1109. public override void WriteByte(byte b)
  1110. {
  1111. lock (_stream)
  1112. _stream.WriteByte(b);
  1113. }
  1114. public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  1115. {
  1116. #if CORERT
  1117. throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251
  1118. #else
  1119. bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite();
  1120. lock (_stream)
  1121. {
  1122. // If the Stream does have its own BeginWrite implementation, then we must use that override.
  1123. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
  1124. // which ensures only one asynchronous operation does so with an asynchronous wait rather
  1125. // than a synchronous wait. A synchronous wait will result in a deadlock condition, because
  1126. // the EndXx method for the outstanding async operation won't be able to acquire the lock on
  1127. // _stream due to this call blocked while holding the lock.
  1128. return overridesBeginWrite ?
  1129. _stream.BeginWrite(buffer, offset, count, callback, state) :
  1130. _stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
  1131. }
  1132. #endif
  1133. }
  1134. public override void EndWrite(IAsyncResult asyncResult)
  1135. {
  1136. if (asyncResult == null)
  1137. throw new ArgumentNullException(nameof(asyncResult));
  1138. lock (_stream)
  1139. _stream.EndWrite(asyncResult);
  1140. }
  1141. }
  1142. }
  1143. }