///<summary> ///Writes asynchronously a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. ///</summary> ///<returns>A Task that represents the asynchronous write.</returns> ///<param name="source">The source.</param> ///<param name="buffer">The buffer containing data to write to the current stream.</param> ///<param name="offset">The zero-based byte offset in at which to begin copying bytes to the current stream.</param> ///<param name="count">The maximum number of bytes to write. </param> /// <param name="cancellationToken">The cancellation token.</param> ///<exception cref="T:System.ArgumentException"> length minus <paramref name="offset" /> is less than <paramref name="count" />. </exception> ///<exception cref="T:System.ArgumentNullException"> is null. </exception> ///<exception cref="T:System.ArgumentOutOfRangeException"> or <paramref name="count" /> is negative. </exception> ///<exception cref="T:System.NotSupportedException">The stream does not support writing. </exception> ///<exception cref="T:System.ObjectDisposedException">The stream is closed. </exception> ///<exception cref="T:System.IO.IOException">An I/O error occurred. </exception> public static Task WriteAsync(this System.IO.Stream source, byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return(TaskServices.FromCancellation(cancellationToken)); } return(Task.Factory.FromAsync(source.BeginWrite, source.EndWrite, buffer, offset, count, null)); }
///<summary> ///Flushes asynchronously the current stream. ///</summary> ///<returns>A Task that represents the asynchronous flush.</returns> public static Task FlushAsync(this System.IO.Stream source, System.Threading.CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return(TaskServices.FromCancellation(cancellationToken)); } return(Task.Factory.StartNew(s => ((System.IO.Stream)s).Flush(), source, cancellationToken, TaskCreationOptions.None, TaskScheduler.Default)); }