Stream.cs 54 KB

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