mscorlib(4.0.0.0) API with additions
Stream.cs
1 using System.Reflection;
5 using System.Security;
7 using System.Threading;
9 
10 namespace System.IO
11 {
13  [Serializable]
14  [ComVisible(true)]
15  [__DynamicallyInvokable]
16  public abstract class Stream : MarshalByRefObject, IDisposable
17  {
18  private struct ReadWriteParameters
19  {
20  internal byte[] Buffer;
21 
22  internal int Offset;
23 
24  internal int Count;
25  }
26 
27  private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction
28  {
29  internal readonly bool _isRead;
30 
31  internal Stream _stream;
32 
33  internal byte[] _buffer;
34 
35  internal int _offset;
36 
37  internal int _count;
38 
39  private AsyncCallback _callback;
40 
41  private ExecutionContext _context;
42 
43  [SecurityCritical]
44  private static ContextCallback s_invokeAsyncCallback;
45 
46  internal void ClearBeginState()
47  {
48  _stream = null;
49  _buffer = null;
50  }
51 
52  [MethodImpl(MethodImplOptions.NoInlining)]
53  [SecuritySafeCritical]
54  public ReadWriteTask(bool isRead, Func<object, int> function, object state, Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback)
55  : base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach)
56  {
57  StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
58  _isRead = isRead;
59  _stream = stream;
60  _buffer = buffer;
61  _offset = offset;
62  _count = count;
63  if (callback != null)
64  {
65  _callback = callback;
66  _context = ExecutionContext.Capture(ref stackMark, ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase);
67  AddCompletionAction(this);
68  }
69  }
70 
71  [SecurityCritical]
72  private static void InvokeAsyncCallback(object completedTask)
73  {
74  ReadWriteTask readWriteTask = (ReadWriteTask)completedTask;
75  AsyncCallback callback = readWriteTask._callback;
76  readWriteTask._callback = null;
77  callback(readWriteTask);
78  }
79 
80  [SecuritySafeCritical]
81  void ITaskCompletionAction.Invoke(Task completingTask)
82  {
83  ExecutionContext context = _context;
84  if (context == null)
85  {
86  AsyncCallback callback = _callback;
87  _callback = null;
88  callback(completingTask);
89  }
90  else
91  {
92  _context = null;
93  ContextCallback callback2 = InvokeAsyncCallback;
94  using (context)
95  {
96  ExecutionContext.Run(context, callback2, this, preserveSyncCtx: true);
97  }
98  }
99  }
100  }
101 
102  [Serializable]
103  private sealed class NullStream : Stream
104  {
105  private static Task<int> s_nullReadTask;
106 
107  public override bool CanRead => true;
108 
109  public override bool CanWrite => true;
110 
111  public override bool CanSeek => true;
112 
113  public override long Length => 0L;
114 
115  public override long Position
116  {
117  get
118  {
119  return 0L;
120  }
121  set
122  {
123  }
124  }
125 
126  internal NullStream()
127  {
128  }
129 
130  protected override void Dispose(bool disposing)
131  {
132  }
133 
134  public override void Flush()
135  {
136  }
137 
138  [ComVisible(false)]
139  public override Task FlushAsync(CancellationToken cancellationToken)
140  {
141  if (!cancellationToken.IsCancellationRequested)
142  {
143  return Task.CompletedTask;
144  }
145  return Task.FromCancellation(cancellationToken);
146  }
147 
148  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
149  public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
150  {
151  if (!CanRead)
152  {
153  __Error.ReadNotSupported();
154  }
155  return BlockingBeginRead(buffer, offset, count, callback, state);
156  }
157 
158  public override int EndRead(IAsyncResult asyncResult)
159  {
160  if (asyncResult == null)
161  {
162  throw new ArgumentNullException("asyncResult");
163  }
164  return BlockingEndRead(asyncResult);
165  }
166 
167  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
168  public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
169  {
170  if (!CanWrite)
171  {
172  __Error.WriteNotSupported();
173  }
174  return BlockingBeginWrite(buffer, offset, count, callback, state);
175  }
176 
177  public override void EndWrite(IAsyncResult asyncResult)
178  {
179  if (asyncResult == null)
180  {
181  throw new ArgumentNullException("asyncResult");
182  }
183  BlockingEndWrite(asyncResult);
184  }
185 
186  public override int Read([In] [Out] byte[] buffer, int offset, int count)
187  {
188  return 0;
189  }
190 
191  [ComVisible(false)]
192  public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
193  {
194  Task<int> task = s_nullReadTask;
195  if (task == null)
196  {
197  task = (s_nullReadTask = new Task<int>(canceled: false, 0, (TaskCreationOptions)16384, CancellationToken.None));
198  }
199  return task;
200  }
201 
202  public override int ReadByte()
203  {
204  return -1;
205  }
206 
207  public override void Write(byte[] buffer, int offset, int count)
208  {
209  }
210 
211  [ComVisible(false)]
212  public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
213  {
214  if (!cancellationToken.IsCancellationRequested)
215  {
216  return Task.CompletedTask;
217  }
218  return Task.FromCancellation(cancellationToken);
219  }
220 
221  public override void WriteByte(byte value)
222  {
223  }
224 
225  public override long Seek(long offset, SeekOrigin origin)
226  {
227  return 0L;
228  }
229 
230  public override void SetLength(long length)
231  {
232  }
233  }
234 
235  internal sealed class SynchronousAsyncResult : IAsyncResult
236  {
237  private readonly object _stateObject;
238 
239  private readonly bool _isWrite;
240 
241  private ManualResetEvent _waitHandle;
242 
243  private ExceptionDispatchInfo _exceptionInfo;
244 
245  private bool _endXxxCalled;
246 
247  private int _bytesRead;
248 
249  public bool IsCompleted => true;
250 
251  public WaitHandle AsyncWaitHandle => LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(initialState: true));
252 
253  public object AsyncState => _stateObject;
254 
255  public bool CompletedSynchronously => true;
256 
257  internal SynchronousAsyncResult(int bytesRead, object asyncStateObject)
258  {
259  _bytesRead = bytesRead;
260  _stateObject = asyncStateObject;
261  }
262 
263  internal SynchronousAsyncResult(object asyncStateObject)
264  {
265  _stateObject = asyncStateObject;
266  _isWrite = true;
267  }
268 
269  internal SynchronousAsyncResult(Exception ex, object asyncStateObject, bool isWrite)
270  {
271  _exceptionInfo = ExceptionDispatchInfo.Capture(ex);
272  _stateObject = asyncStateObject;
273  _isWrite = isWrite;
274  }
275 
276  internal void ThrowIfError()
277  {
278  if (_exceptionInfo != null)
279  {
280  _exceptionInfo.Throw();
281  }
282  }
283 
284  internal static int EndRead(IAsyncResult asyncResult)
285  {
286  SynchronousAsyncResult synchronousAsyncResult = asyncResult as SynchronousAsyncResult;
287  if (synchronousAsyncResult == null || synchronousAsyncResult._isWrite)
288  {
289  __Error.WrongAsyncResult();
290  }
291  if (synchronousAsyncResult._endXxxCalled)
292  {
293  __Error.EndReadCalledTwice();
294  }
295  synchronousAsyncResult._endXxxCalled = true;
296  synchronousAsyncResult.ThrowIfError();
297  return synchronousAsyncResult._bytesRead;
298  }
299 
300  internal static void EndWrite(IAsyncResult asyncResult)
301  {
302  SynchronousAsyncResult synchronousAsyncResult = asyncResult as SynchronousAsyncResult;
303  if (synchronousAsyncResult == null || !synchronousAsyncResult._isWrite)
304  {
305  __Error.WrongAsyncResult();
306  }
307  if (synchronousAsyncResult._endXxxCalled)
308  {
309  __Error.EndWriteCalledTwice();
310  }
311  synchronousAsyncResult._endXxxCalled = true;
312  synchronousAsyncResult.ThrowIfError();
313  }
314  }
315 
316  [Serializable]
317  internal sealed class SyncStream : Stream, IDisposable
318  {
319  private Stream _stream;
320 
321  [NonSerialized]
322  private bool? _overridesBeginRead;
323 
324  [NonSerialized]
325  private bool? _overridesBeginWrite;
326 
327  public override bool CanRead => _stream.CanRead;
328 
329  public override bool CanWrite => _stream.CanWrite;
330 
331  public override bool CanSeek => _stream.CanSeek;
332 
333  [ComVisible(false)]
334  public override bool CanTimeout
335  {
336  get
337  {
338  return _stream.CanTimeout;
339  }
340  }
341 
342  public override long Length
343  {
344  get
345  {
346  lock (_stream)
347  {
348  return _stream.Length;
349  }
350  }
351  }
352 
353  public override long Position
354  {
355  get
356  {
357  lock (_stream)
358  {
359  return _stream.Position;
360  }
361  }
362  set
363  {
364  lock (_stream)
365  {
366  _stream.Position = value;
367  }
368  }
369  }
370 
371  [ComVisible(false)]
372  public override int ReadTimeout
373  {
374  get
375  {
376  return _stream.ReadTimeout;
377  }
378  set
379  {
380  _stream.ReadTimeout = value;
381  }
382  }
383 
384  [ComVisible(false)]
385  public override int WriteTimeout
386  {
387  get
388  {
389  return _stream.WriteTimeout;
390  }
391  set
392  {
393  _stream.WriteTimeout = value;
394  }
395  }
396 
397  internal SyncStream(Stream stream)
398  {
399  if (stream == null)
400  {
401  throw new ArgumentNullException("stream");
402  }
403  _stream = stream;
404  }
405 
406  public override void Close()
407  {
408  lock (_stream)
409  {
410  try
411  {
412  _stream.Close();
413  }
414  finally
415  {
416  base.Dispose(disposing: true);
417  }
418  }
419  }
420 
421  protected override void Dispose(bool disposing)
422  {
423  lock (_stream)
424  {
425  try
426  {
427  if (disposing)
428  {
429  ((IDisposable)_stream).Dispose();
430  }
431  }
432  finally
433  {
434  base.Dispose(disposing);
435  }
436  }
437  }
438 
439  public override void Flush()
440  {
441  lock (_stream)
442  {
443  _stream.Flush();
444  }
445  }
446 
447  public override int Read([In] [Out] byte[] bytes, int offset, int count)
448  {
449  lock (_stream)
450  {
451  return _stream.Read(bytes, offset, count);
452  }
453  }
454 
455  public override int ReadByte()
456  {
457  lock (_stream)
458  {
459  return _stream.ReadByte();
460  }
461  }
462 
463  private static bool OverridesBeginMethod(Stream stream, string methodName)
464  {
465  MethodInfo[] methods = stream.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public);
466  MethodInfo[] array = methods;
467  foreach (MethodInfo methodInfo in array)
468  {
469  if (methodInfo.DeclaringType == typeof(Stream) && methodInfo.Name == methodName)
470  {
471  return false;
472  }
473  }
474  return true;
475  }
476 
477  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
478  public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
479  {
480  if (!_overridesBeginRead.HasValue)
481  {
482  _overridesBeginRead = OverridesBeginMethod(_stream, "BeginRead");
483  }
484  lock (_stream)
485  {
486  return _overridesBeginRead.Value ? _stream.BeginRead(buffer, offset, count, callback, state) : _stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true);
487  }
488  }
489 
490  public override int EndRead(IAsyncResult asyncResult)
491  {
492  if (asyncResult == null)
493  {
494  throw new ArgumentNullException("asyncResult");
495  }
496  lock (_stream)
497  {
498  return _stream.EndRead(asyncResult);
499  }
500  }
501 
502  public override long Seek(long offset, SeekOrigin origin)
503  {
504  lock (_stream)
505  {
506  return _stream.Seek(offset, origin);
507  }
508  }
509 
510  public override void SetLength(long length)
511  {
512  lock (_stream)
513  {
514  _stream.SetLength(length);
515  }
516  }
517 
518  public override void Write(byte[] bytes, int offset, int count)
519  {
520  lock (_stream)
521  {
522  _stream.Write(bytes, offset, count);
523  }
524  }
525 
526  public override void WriteByte(byte b)
527  {
528  lock (_stream)
529  {
530  _stream.WriteByte(b);
531  }
532  }
533 
534  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
535  public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
536  {
537  if (!_overridesBeginWrite.HasValue)
538  {
539  _overridesBeginWrite = OverridesBeginMethod(_stream, "BeginWrite");
540  }
541  lock (_stream)
542  {
543  return _overridesBeginWrite.Value ? _stream.BeginWrite(buffer, offset, count, callback, state) : _stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true);
544  }
545  }
546 
547  public override void EndWrite(IAsyncResult asyncResult)
548  {
549  if (asyncResult == null)
550  {
551  throw new ArgumentNullException("asyncResult");
552  }
553  lock (_stream)
554  {
555  _stream.EndWrite(asyncResult);
556  }
557  }
558  }
559 
561  [__DynamicallyInvokable]
562  public static readonly Stream Null = new NullStream();
563 
564  private const int _DefaultCopyBufferSize = 81920;
565 
566  [NonSerialized]
567  private ReadWriteTask _activeReadWriteTask;
568 
569  [NonSerialized]
570  private SemaphoreSlim _asyncActiveSemaphore;
571 
575  [__DynamicallyInvokable]
576  public abstract bool CanRead
577  {
578  [__DynamicallyInvokable]
579  get;
580  }
581 
585  [__DynamicallyInvokable]
586  public abstract bool CanSeek
587  {
588  [__DynamicallyInvokable]
589  get;
590  }
591 
594  [ComVisible(false)]
595  [__DynamicallyInvokable]
596  public virtual bool CanTimeout
597  {
598  [__DynamicallyInvokable]
599  get
600  {
601  return false;
602  }
603  }
604 
608  [__DynamicallyInvokable]
609  public abstract bool CanWrite
610  {
611  [__DynamicallyInvokable]
612  get;
613  }
614 
619  [__DynamicallyInvokable]
620  public abstract long Length
621  {
622  [__DynamicallyInvokable]
623  get;
624  }
625 
631  [__DynamicallyInvokable]
632  public abstract long Position
633  {
634  [__DynamicallyInvokable]
635  get;
636  [__DynamicallyInvokable]
637  set;
638  }
639 
643  [ComVisible(false)]
644  [__DynamicallyInvokable]
645  public virtual int ReadTimeout
646  {
647  [__DynamicallyInvokable]
648  get
649  {
650  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
651  }
652  [__DynamicallyInvokable]
653  set
654  {
655  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
656  }
657  }
658 
662  [ComVisible(false)]
663  [__DynamicallyInvokable]
664  public virtual int WriteTimeout
665  {
666  [__DynamicallyInvokable]
667  get
668  {
669  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
670  }
671  [__DynamicallyInvokable]
672  set
673  {
674  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
675  }
676  }
677 
678  internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
679  {
680  return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
681  }
682 
690  [ComVisible(false)]
691  [__DynamicallyInvokable]
692  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
693  public Task CopyToAsync(Stream destination)
694  {
695  return CopyToAsync(destination, 81920);
696  }
697 
708  [ComVisible(false)]
709  [__DynamicallyInvokable]
710  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
711  public Task CopyToAsync(Stream destination, int bufferSize)
712  {
713  return CopyToAsync(destination, bufferSize, CancellationToken.None);
714  }
715 
727  [ComVisible(false)]
728  [__DynamicallyInvokable]
729  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
730  public virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
731  {
732  if (destination == null)
733  {
734  throw new ArgumentNullException("destination");
735  }
736  if (bufferSize <= 0)
737  {
738  throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
739  }
740  if (!CanRead && !CanWrite)
741  {
742  throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
743  }
744  if (!destination.CanRead && !destination.CanWrite)
745  {
746  throw new ObjectDisposedException("destination", Environment.GetResourceString("ObjectDisposed_StreamClosed"));
747  }
748  if (!CanRead)
749  {
750  throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
751  }
752  if (!destination.CanWrite)
753  {
754  throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
755  }
756  return CopyToAsyncInternal(destination, bufferSize, cancellationToken);
757  }
758 
759  private async Task CopyToAsyncInternal(Stream destination, int bufferSize, CancellationToken cancellationToken)
760  {
761  byte[] buffer = new byte[bufferSize];
762  int bytesRead;
763  while ((bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)) != 0)
764  {
765  await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
766  }
767  }
768 
777  [__DynamicallyInvokable]
778  public void CopyTo(Stream destination)
779  {
780  if (destination == null)
781  {
782  throw new ArgumentNullException("destination");
783  }
784  if (!CanRead && !CanWrite)
785  {
786  throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
787  }
788  if (!destination.CanRead && !destination.CanWrite)
789  {
790  throw new ObjectDisposedException("destination", Environment.GetResourceString("ObjectDisposed_StreamClosed"));
791  }
792  if (!CanRead)
793  {
794  throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
795  }
796  if (!destination.CanWrite)
797  {
798  throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
799  }
800  InternalCopyTo(destination, 81920);
801  }
802 
814  [__DynamicallyInvokable]
815  public void CopyTo(Stream destination, int bufferSize)
816  {
817  if (destination == null)
818  {
819  throw new ArgumentNullException("destination");
820  }
821  if (bufferSize <= 0)
822  {
823  throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
824  }
825  if (!CanRead && !CanWrite)
826  {
827  throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
828  }
829  if (!destination.CanRead && !destination.CanWrite)
830  {
831  throw new ObjectDisposedException("destination", Environment.GetResourceString("ObjectDisposed_StreamClosed"));
832  }
833  if (!CanRead)
834  {
835  throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
836  }
837  if (!destination.CanWrite)
838  {
839  throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
840  }
841  InternalCopyTo(destination, bufferSize);
842  }
843 
844  private void InternalCopyTo(Stream destination, int bufferSize)
845  {
846  byte[] array = new byte[bufferSize];
847  int count;
848  while ((count = Read(array, 0, array.Length)) != 0)
849  {
850  destination.Write(array, 0, count);
851  }
852  }
853 
855  public virtual void Close()
856  {
857  Dispose(disposing: true);
858  GC.SuppressFinalize(this);
859  }
860 
862  [__DynamicallyInvokable]
863  public void Dispose()
864  {
865  Close();
866  }
867 
871  [__DynamicallyInvokable]
872  protected virtual void Dispose(bool disposing)
873  {
874  }
875 
878  [__DynamicallyInvokable]
879  public abstract void Flush();
880 
884  [ComVisible(false)]
885  [__DynamicallyInvokable]
886  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
887  public Task FlushAsync()
888  {
890  }
891 
896  [ComVisible(false)]
897  [__DynamicallyInvokable]
898  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
899  public virtual Task FlushAsync(CancellationToken cancellationToken)
900  {
901  return Task.Factory.StartNew(delegate(object state)
902  {
903  ((Stream)state).Flush();
904  }, this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
905  }
906 
909  [Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")]
910  protected virtual WaitHandle CreateWaitHandle()
911  {
912  return new ManualResetEvent(initialState: false);
913  }
914 
926  [__DynamicallyInvokable]
927  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
928  public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
929  {
930  return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false);
931  }
932 
933  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
934  internal IAsyncResult BeginReadInternal(byte[] buffer, int offset, int count, AsyncCallback callback, object state, bool serializeAsynchronously)
935  {
936  if (!CanRead)
937  {
938  __Error.ReadNotSupported();
939  }
940  if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
941  {
942  return BlockingBeginRead(buffer, offset, count, callback, state);
943  }
944  SemaphoreSlim semaphoreSlim = EnsureAsyncActiveSemaphoreInitialized();
945  Task task = null;
946  if (serializeAsynchronously)
947  {
948  task = semaphoreSlim.WaitAsync();
949  }
950  else
951  {
952  semaphoreSlim.Wait();
953  }
954  ReadWriteTask readWriteTask = new ReadWriteTask(isRead: true, delegate
955  {
956  ReadWriteTask readWriteTask2 = Task.InternalCurrent as ReadWriteTask;
957  int result = readWriteTask2._stream.Read(readWriteTask2._buffer, readWriteTask2._offset, readWriteTask2._count);
958  readWriteTask2.ClearBeginState();
959  return result;
960  }, state, this, buffer, offset, count, callback);
961  if (task != null)
962  {
963  RunReadWriteTaskWhenReady(task, readWriteTask);
964  }
965  else
966  {
967  RunReadWriteTask(readWriteTask);
968  }
969  return readWriteTask;
970  }
971 
981  [__DynamicallyInvokable]
982  public virtual int EndRead(IAsyncResult asyncResult)
983  {
984  if (asyncResult == null)
985  {
986  throw new ArgumentNullException("asyncResult");
987  }
988  if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
989  {
990  return BlockingEndRead(asyncResult);
991  }
992  ReadWriteTask activeReadWriteTask = _activeReadWriteTask;
993  if (activeReadWriteTask == null)
994  {
995  throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
996  }
997  if (activeReadWriteTask != asyncResult)
998  {
999  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
1000  }
1001  if (!activeReadWriteTask._isRead)
1002  {
1003  throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
1004  }
1005  try
1006  {
1007  return activeReadWriteTask.GetAwaiter().GetResult();
1008  }
1009  finally
1010  {
1011  _activeReadWriteTask = null;
1012  _asyncActiveSemaphore.Release();
1013  }
1014  }
1015 
1029  [ComVisible(false)]
1030  [__DynamicallyInvokable]
1031  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
1032  public Task<int> ReadAsync(byte[] buffer, int offset, int count)
1033  {
1034  return ReadAsync(buffer, offset, count, CancellationToken.None);
1035  }
1036 
1051  [ComVisible(false)]
1052  [__DynamicallyInvokable]
1053  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
1054  public virtual Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
1055  {
1056  if (!cancellationToken.IsCancellationRequested)
1057  {
1058  return BeginEndReadAsync(buffer, offset, count);
1059  }
1060  return Task.FromCancellation<int>(cancellationToken);
1061  }
1062 
1063  private Task<int> BeginEndReadAsync(byte[] buffer, int offset, int count)
1064  {
1065  return TaskFactory<int>.FromAsyncTrim(this, new ReadWriteParameters
1066  {
1067  Buffer = buffer,
1068  Offset = offset,
1069  Count = count
1070  }, (Stream stream, ReadWriteParameters args, AsyncCallback callback, object state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), (Stream stream, IAsyncResult asyncResult) => stream.EndRead(asyncResult));
1071  }
1072 
1084  [__DynamicallyInvokable]
1085  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
1086  public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
1087  {
1088  return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false);
1089  }
1090 
1091  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
1092  internal IAsyncResult BeginWriteInternal(byte[] buffer, int offset, int count, AsyncCallback callback, object state, bool serializeAsynchronously)
1093  {
1094  if (!CanWrite)
1095  {
1096  __Error.WriteNotSupported();
1097  }
1098  if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
1099  {
1100  return BlockingBeginWrite(buffer, offset, count, callback, state);
1101  }
1102  SemaphoreSlim semaphoreSlim = EnsureAsyncActiveSemaphoreInitialized();
1103  Task task = null;
1104  if (serializeAsynchronously)
1105  {
1106  task = semaphoreSlim.WaitAsync();
1107  }
1108  else
1109  {
1110  semaphoreSlim.Wait();
1111  }
1112  ReadWriteTask readWriteTask = new ReadWriteTask(isRead: false, delegate
1113  {
1114  ReadWriteTask readWriteTask2 = Task.InternalCurrent as ReadWriteTask;
1115  readWriteTask2._stream.Write(readWriteTask2._buffer, readWriteTask2._offset, readWriteTask2._count);
1116  readWriteTask2.ClearBeginState();
1117  return 0;
1118  }, state, this, buffer, offset, count, callback);
1119  if (task != null)
1120  {
1121  RunReadWriteTaskWhenReady(task, readWriteTask);
1122  }
1123  else
1124  {
1125  RunReadWriteTask(readWriteTask);
1126  }
1127  return readWriteTask;
1128  }
1129 
1130  private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask)
1131  {
1132  if (asyncWaiter.IsCompleted)
1133  {
1134  RunReadWriteTask(readWriteTask);
1135  }
1136  else
1137  {
1138  asyncWaiter.ContinueWith(delegate(Task t, object state)
1139  {
1140  Tuple<Stream, ReadWriteTask> tuple = (Tuple<Stream, ReadWriteTask>)state;
1141  tuple.Item1.RunReadWriteTask(tuple.Item2);
1142  }, Tuple.Create(this, readWriteTask), default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
1143  }
1144  }
1145 
1146  private void RunReadWriteTask(ReadWriteTask readWriteTask)
1147  {
1148  _activeReadWriteTask = readWriteTask;
1149  readWriteTask.m_taskScheduler = TaskScheduler.Default;
1150  readWriteTask.ScheduleAndStart(needsProtection: false);
1151  }
1152 
1161  [__DynamicallyInvokable]
1162  public virtual void EndWrite(IAsyncResult asyncResult)
1163  {
1164  if (asyncResult == null)
1165  {
1166  throw new ArgumentNullException("asyncResult");
1167  }
1168  if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
1169  {
1170  BlockingEndWrite(asyncResult);
1171  return;
1172  }
1173  ReadWriteTask activeReadWriteTask = _activeReadWriteTask;
1174  if (activeReadWriteTask == null)
1175  {
1176  throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
1177  }
1178  if (activeReadWriteTask != asyncResult)
1179  {
1180  throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
1181  }
1182  if (activeReadWriteTask._isRead)
1183  {
1184  throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
1185  }
1186  try
1187  {
1188  activeReadWriteTask.GetAwaiter().GetResult();
1189  }
1190  finally
1191  {
1192  _activeReadWriteTask = null;
1193  _asyncActiveSemaphore.Release();
1194  }
1195  }
1196 
1210  [ComVisible(false)]
1211  [__DynamicallyInvokable]
1212  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
1213  public Task WriteAsync(byte[] buffer, int offset, int count)
1214  {
1215  return WriteAsync(buffer, offset, count, CancellationToken.None);
1216  }
1217 
1232  [ComVisible(false)]
1233  [__DynamicallyInvokable]
1234  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
1235  public virtual Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
1236  {
1237  if (!cancellationToken.IsCancellationRequested)
1238  {
1239  return BeginEndWriteAsync(buffer, offset, count);
1240  }
1241  return Task.FromCancellation(cancellationToken);
1242  }
1243 
1244  private Task BeginEndWriteAsync(byte[] buffer, int offset, int count)
1245  {
1246  return TaskFactory<VoidTaskResult>.FromAsyncTrim(this, new ReadWriteParameters
1247  {
1248  Buffer = buffer,
1249  Offset = offset,
1250  Count = count
1251  }, (Stream stream, ReadWriteParameters args, AsyncCallback callback, object state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), delegate(Stream stream, IAsyncResult asyncResult)
1252  {
1253  stream.EndWrite(asyncResult);
1254  return default(VoidTaskResult);
1255  });
1256  }
1257 
1265  [__DynamicallyInvokable]
1266  public abstract long Seek(long offset, SeekOrigin origin);
1267 
1273  [__DynamicallyInvokable]
1274  public abstract void SetLength(long value);
1275 
1289  [__DynamicallyInvokable]
1290  public abstract int Read([In] [Out] byte[] buffer, int offset, int count);
1291 
1296  [__DynamicallyInvokable]
1297  public virtual int ReadByte()
1298  {
1299  byte[] array = new byte[1];
1300  if (Read(array, 0, 1) == 0)
1301  {
1302  return -1;
1303  }
1304  return array[0];
1305  }
1306 
1320  [__DynamicallyInvokable]
1321  public abstract void Write(byte[] buffer, int offset, int count);
1322 
1328  [__DynamicallyInvokable]
1329  public virtual void WriteByte(byte value)
1330  {
1331  Write(new byte[1]
1332  {
1333  value
1334  }, 0, 1);
1335  }
1336 
1342  [HostProtection(SecurityAction.LinkDemand, Synchronization = true)]
1343  public static Stream Synchronized(Stream stream)
1344  {
1345  if (stream == null)
1346  {
1347  throw new ArgumentNullException("stream");
1348  }
1349  if (stream is SyncStream)
1350  {
1351  return stream;
1352  }
1353  return new SyncStream(stream);
1354  }
1355 
1357  [Obsolete("Do not call or override this method.")]
1358  protected virtual void ObjectInvariant()
1359  {
1360  }
1361 
1362  internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
1363  {
1364  SynchronousAsyncResult synchronousAsyncResult;
1365  try
1366  {
1367  int bytesRead = Read(buffer, offset, count);
1368  synchronousAsyncResult = new SynchronousAsyncResult(bytesRead, state);
1369  }
1370  catch (IOException ex)
1371  {
1372  synchronousAsyncResult = new SynchronousAsyncResult(ex, state, isWrite: false);
1373  }
1374  callback?.Invoke(synchronousAsyncResult);
1375  return synchronousAsyncResult;
1376  }
1377 
1378  internal static int BlockingEndRead(IAsyncResult asyncResult)
1379  {
1380  return SynchronousAsyncResult.EndRead(asyncResult);
1381  }
1382 
1383  internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
1384  {
1385  SynchronousAsyncResult synchronousAsyncResult;
1386  try
1387  {
1388  Write(buffer, offset, count);
1389  synchronousAsyncResult = new SynchronousAsyncResult(state);
1390  }
1391  catch (IOException ex)
1392  {
1393  synchronousAsyncResult = new SynchronousAsyncResult(ex, state, isWrite: true);
1394  }
1395  callback?.Invoke(synchronousAsyncResult);
1396  return synchronousAsyncResult;
1397  }
1398 
1399  internal static void BlockingEndWrite(IAsyncResult asyncResult)
1400  {
1401  SynchronousAsyncResult.EndWrite(asyncResult);
1402  }
1403 
1405  [__DynamicallyInvokable]
1406  protected Stream()
1407  {
1408  }
1409  }
1410 }
static new TaskFactory< TResult > Factory
Provides access to factory methods for creating and configuring T:System.Threading....
Definition: Task.cs:75
Represents a lightweight alternative to T:System.Threading.Semaphore that limits the number of thread...
abstract void Write(byte[] buffer, int offset, int count)
When overridden in a derived class, writes a sequence of bytes to the current stream and advances the...
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
abstract int Read([In] [Out] byte[] buffer, int offset, int count)
When overridden in a derived class, reads a sequence of bytes from the current stream and advances th...
Propagates notification that operations should be canceled.
new ConfiguredTaskAwaitable< TResult > ConfigureAwait(bool continueOnCapturedContext)
Configures an awaiter used to await this T:System.Threading.Tasks.Task`1.
Definition: Task.cs:393
delegate void ContextCallback(object state)
Represents a method to be called within a new context.
Encapsulates operating system–specific objects that wait for exclusive access to shared resources.
Definition: WaitHandle.cs:15
virtual void Dispose(bool disposing)
Releases the unmanaged resources used by the T:System.IO.Stream and optionally releases the managed r...
Definition: Stream.cs:872
virtual Task FlushAsync(CancellationToken cancellationToken)
Asynchronously clears all buffers for this stream, causes any buffered data to be written to the unde...
Definition: Stream.cs:899
Stream()
Initializes a new instance of the T:System.IO.Stream class.
Definition: Stream.cs:1406
static void SuppressFinalize(object obj)
Requests that the common language runtime not call the finalizer for the specified object.
Definition: GC.cs:308
Discovers the attributes of a method and provides access to method metadata.
Definition: MethodInfo.cs:13
abstract bool CanSeek
When overridden in a derived class, gets a value indicating whether the current stream supports seeki...
Definition: Stream.cs:587
void Throw()
Throws the exception that is represented by the current T:System.Runtime.ExceptionServices....
virtual int WriteTimeout
Gets or sets a value, in miliseconds, that determines how long the stream will attempt to write befor...
Definition: Stream.cs:665
Provides a mechanism for releasing unmanaged resources.To browse the .NET Framework source code for t...
Definition: IDisposable.cs:8
Represents an object that handles the low-level work of queuing tasks onto threads.
BindingFlags
Specifies flags that control binding and the way in which the search for members and types is conduct...
Definition: BindingFlags.cs:10
Definition: __Canon.cs:3
TaskContinuationOptions
Specifies the behavior for a task that is created by using the M:System.Threading....
The exception that is thrown when the value of an argument is outside the allowable range of values a...
abstract bool CanWrite
When overridden in a derived class, gets a value indicating whether the current stream supports writi...
Definition: Stream.cs:610
delegate void AsyncCallback(IAsyncResult ar)
References a method to be called when a corresponding asynchronous operation completes.
virtual void WriteByte(byte value)
Writes a byte to the current position in the stream and advances the position within the stream by on...
Definition: Stream.cs:1329
bool IsCancellationRequested
Gets whether cancellation has been requested for this token.
Task< int > ReadAsync(byte[] buffer, int offset, int count)
Asynchronously reads a sequence of bytes from the current stream and advances the position within the...
Definition: Stream.cs:1032
abstract void SetLength(long value)
When overridden in a derived class, sets the length of the current stream.
SeekOrigin
Specifies the position in a stream to use for seeking.
Definition: SeekOrigin.cs:9
TaskCreationOptions
Specifies flags that control optional behavior for the creation and execution of tasks.
virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
Begins an asynchronous read operation. (Consider using M:System.IO.Stream.ReadAsync(System....
Definition: Stream.cs:928
static ExceptionDispatchInfo Capture(Exception source)
Creates an T:System.Runtime.ExceptionServices.ExceptionDispatchInfo object that represents the specif...
The exception that is thrown when an operation is performed on a disposed object.
Task CopyToAsync(Stream destination)
Asynchronously reads the bytes from the current stream and writes them to another stream.
Definition: Stream.cs:693
abstract bool CanRead
When overridden in a derived class, gets a value indicating whether the current stream supports readi...
Definition: Stream.cs:577
Represents an exception whose state is captured at a certain point in code.
static TaskScheduler Default
Gets the default T:System.Threading.Tasks.TaskScheduler instance that is provided by the ....
SecurityAction
Specifies the security actions that can be performed using declarative security.
Provides information about, and means to manipulate, the current environment and platform....
Definition: Environment.cs:21
virtual void Close()
Closes the current stream and releases any resources (such as sockets and file handles) associated wi...
Definition: Stream.cs:855
Represents the status of an asynchronous operation.
Definition: IAsyncResult.cs:9
Manages the execution context for the current thread. This class cannot be inherited.
Task CopyToAsync(Stream destination, int bufferSize)
Asynchronously reads the bytes from the current stream and writes them to another stream,...
Definition: Stream.cs:711
static readonly Stream Null
A Stream with no backing store.
Definition: Stream.cs:562
Provides lazy initialization routines.
bool IsCompleted
Gets whether this T:System.Threading.Tasks.Task has completed.
Definition: Task.cs:1370
virtual int ReadTimeout
Gets or sets a value, in miliseconds, that determines how long the stream will attempt to read before...
Definition: Stream.cs:646
Task WaitAsync()
Asynchronously waits to enter the T:System.Threading.SemaphoreSlim.
Task FlushAsync()
Asynchronously clears all buffers for this stream and causes any buffered data to be written to the u...
Definition: Stream.cs:887
virtual void ObjectInvariant()
Provides support for a T:System.Diagnostics.Contracts.Contract.
Definition: Stream.cs:1358
abstract void Flush()
When overridden in a derived class, clears all buffers for this stream and causes any buffered data t...
void CopyTo(Stream destination)
Reads the bytes from the current stream and writes them to another stream.
Definition: Stream.cs:778
Notifies one or more waiting threads that an event has occurred. This class cannot be inherited.
void Wait()
Blocks the current thread until it can enter the T:System.Threading.SemaphoreSlim.
virtual int ReadByte()
Reads a byte from the stream and advances the position within the stream by one byte,...
Definition: Stream.cs:1297
static void Run(ExecutionContext executionContext, ContextCallback callback, object state)
Runs a method in a specified execution context on the current thread.
Type DeclaringType
Provides COM objects with version-independent access to the P:System.Reflection.MemberInfo....
Definition: _MethodInfo.cs:31
abstract long Seek(long offset, SeekOrigin origin)
When overridden in a derived class, sets the position within the current stream.
virtual bool CanTimeout
Gets a value that determines whether the current stream can time out.
Definition: Stream.cs:597
static Task CompletedTask
Gets a task that has already completed successfully.
Definition: Task.cs:1453
MethodImplOptions
Defines the details of how a method is implemented.
static CancellationToken None
Returns an empty T:System.Threading.CancellationToken value.
Controls the system garbage collector, a service that automatically reclaims unused memory.
Definition: GC.cs:11
virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
Begins an asynchronous write operation. (Consider using M:System.IO.Stream.WriteAsync(System....
Definition: Stream.cs:1086
static ExecutionContext Capture()
Captures the execution context from the current thread.
The exception that is thrown when one of the arguments provided to a method is not valid.
abstract long Length
When overridden in a derived class, gets the length in bytes of the stream.
Definition: Stream.cs:621
virtual WaitHandle CreateWaitHandle()
Allocates a T:System.Threading.WaitHandle object.
Definition: Stream.cs:910
Represents errors that occur during application execution.To browse the .NET Framework source code fo...
Definition: Exception.cs:22
Creates or manipulates threads other than its own, which might be harmful to the host.
virtual Task< int > ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
Asynchronously reads a sequence of bytes from the current stream, advances the position within the st...
Definition: Stream.cs:1054
static Stream Synchronized(Stream stream)
Creates a thread-safe (synchronized) wrapper around the specified T:System.IO.Stream object.
Definition: Stream.cs:1343
Specifies that the class can be serialized.
abstract long Position
When overridden in a derived class, gets or sets the position within the current stream.
Definition: Stream.cs:633
void Dispose()
Releases all resources used by the T:System.IO.Stream.
Definition: Stream.cs:863
Task WriteAsync(byte[] buffer, int offset, int count)
Asynchronously writes a sequence of bytes to the current stream and advances the current position wit...
Definition: Stream.cs:1213
The exception that is thrown when a method call is invalid for the object's current state.
Manipulates arrays of primitive types.
Definition: Buffer.cs:11
Task ContinueWith(Action< Task< TResult >> continuationAction)
Creates a continuation that executes asynchronously when the target task completes.
Definition: Task.cs:405
string Name
Provides COM objects with version-independent access to the P:System.Reflection.MemberInfo....
Definition: _MethodInfo.cs:24
virtual int EndRead(IAsyncResult asyncResult)
Waits for the pending asynchronous read to complete. (Consider using M:System.IO.Stream....
Definition: Stream.cs:982
virtual Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
Asynchronously writes a sequence of bytes to the current stream, advances the current position within...
Definition: Stream.cs:1235
The exception that is thrown when an invoked method is not supported, or when there is an attempt to ...
Provides support for creating and scheduling T:System.Threading.Tasks.Task`1 objects.
Definition: TaskFactory.cs:12
virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
Asynchronously reads the bytes from the current stream and writes them to another stream,...
Definition: Stream.cs:730
virtual void EndWrite(IAsyncResult asyncResult)
Ends an asynchronous write operation. (Consider using M:System.IO.Stream.WriteAsync(System....
Definition: Stream.cs:1162
void CopyTo(Stream destination, int bufferSize)
Reads the bytes from the current stream and writes them to another stream, using a specified buffer s...
Definition: Stream.cs:815
Represents an asynchronous operation that can return a value.
Definition: Task.cs:18
Provides a generic view of a sequence of bytes. This is an abstract class.To browse the ....
Definition: Stream.cs:16
Enables access to objects across application domain boundaries in applications that support remoting.