public IAsyncOperationWithProgress<IBuffer, uint> ReadAsync (IBuffer buffer, uint count, InputStreamOptions options) { if (disposed) throw new ObjectDisposedException(GetType().FullName); throw new NotImplementedException(); }
public async Task<IBuffer> ReadPrivateAsync(IProgress<uint> progress, IBuffer buffer, uint count, InputStreamOptions options) { progress.Report(0); buffer = await _stream.ReadAsync( buffer, count, options); progress.Report(50); _sha.Append(buffer); progress.Report(100); return buffer; }
public IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return AsyncInfo.Run<IBuffer, uint>((token, progress) => { IBuffer buff = new byte[0].AsBuffer(); if (indexCounter < _byteStreamParts.Count()) { buff = _byteStreamParts.ElementAt(indexCounter).AsBuffer(); } indexCounter++; return Task.FromResult(buff); }); }
internal async Task<StreamReadResult> ReadAsync(uint bufferSize, InputStreamOptions streamOptions) { IBuffer response = null; int retryCounter = 0; do { var buffer = (new byte[bufferSize]).AsBuffer(); response = await _requestStream.ReadAsync(buffer, bufferSize, streamOptions); if (response.Length == 0) { await Task.Delay(INPUTSTREAM_EMPTY_DELAYMS[retryCounter]); retryCounter++; } } while (response.Length == 0 && retryCounter < INPUTSTREAM_EMPTY_DELAYMS.Length); bool succeed = response.Length > 0; byte[] data = succeed ? response.ToArray() : new byte[0]; return new StreamReadResult(data, succeed); }
public IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return AsyncInfo.Run<IBuffer, uint>(async (token, progress) => { var pieceSize = _torrent.PieceLength; var pieceStart = (int) ((double) _internalStream.Position/pieceSize); var pieceEnd = (int) ((count + (double) _internalStream.Position)/pieceSize); var total = pieceEnd - pieceStart; if (total == 0) total++; var index = 0; for (var i = pieceStart; i <= pieceEnd; i++) { progress.Report(((uint) index/(uint) total)*100); index++; // missing while (!_torrentFile.BitField[i]) { token.ThrowIfCancellationRequested(); _manager.SlidingPicker.HighPrioritySetStart = i; _manager.SlidingPicker.HighPrioritySetSize = Math.Max(TorrentStreamManager.DefaultPrepareCount, i - pieceEnd); // TODO instead of looping, use event await Task.Delay(500, token); } } var notDownloaded = _torrentFile.BitField.FirstFalse(pieceEnd, _torrentFile.BitField.Length - pieceEnd); if (notDownloaded > -1) { _manager.SlidingPicker.HighPrioritySetStart = notDownloaded; _manager.SlidingPicker.HighPrioritySetSize = TorrentStreamManager.DefaultPrepareCount; } return await _internalStream.ReadAsync(buffer, count, options); }); }
public IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return AsyncInfo.Run<IBuffer, uint>(async (cancellationToken, progress) => { if (length - position < count) { count = length - position; } byte[] data = new byte[count]; for (uint i = 0; i < count; i++) { data[i] = 64; } // Introduce a 1 second delay. await Task.Delay(1000); position += count; progress.Report(count); return data.AsBuffer(); }); }
Windows.Foundation.IAsyncOperationWithProgress<IBuffer, uint> IInputStream.ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { throw new NotImplementedException(); }
IAsyncOperationWithProgress<IBuffer, uint> IInputStream.ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { #if true return AsyncInfo.Run(async delegate (CancellationToken cancel, IProgress<uint> progress) { cancel.ThrowIfCancellationRequested(); buffer.Length = Read(buffer, buffer.Length, count); progress.Report(buffer.Length); return buffer; }); #else return AsyncInfo.Run((CancellationToken cancel, IProgress<uint> progress) => { var task = new Task<IBuffer>(() => { cancel.ThrowIfCancellationRequested(); buffer.Length = Read(buffer, buffer.Length, count); progress.Report(buffer.Length); return buffer; }, cancel); task.Start(); return task; }); #endif }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) => throw new NotImplementedException();
private static void DoTestRead(Func <IInputStream> createStreamFunc, InputStreamOptions inputStreamOptions, bool mustInvokeProgressHandler, bool completesSynchronously) { IInputStream stream = createStreamFunc(); IBuffer buffer = WindowsRuntimeBuffer.Create(TestStreamProvider.ModelStreamLength); IAsyncOperationWithProgress <IBuffer, uint> readOp = stream.ReadAsync(buffer, (uint)TestStreamProvider.ModelStreamLength, inputStreamOptions); if (completesSynchronously) { // New readOp for a stream where we know that reading is sycnhronous must have Status = Completed Assert.Equal(AsyncStatus.Completed, readOp.Status); } else { // Note the race. By the tie we get here, the status of the op may be started or already completed. AsyncStatus readOpStatus = readOp.Status; Assert.True(readOpStatus == AsyncStatus.Completed || readOpStatus == AsyncStatus.Started, "New readOp must have Status = Started or Completed (race)"); } bool progressCallbackInvoked = false; bool completedCallbackInvoked = false; uint readOpId = readOp.Id; EventWaitHandle waitHandle = new ManualResetEvent(false); readOp.Progress = (asyncReadOp, bytesCompleted) => { progressCallbackInvoked = true; // asyncReadOp.Id in a progress callback must match the ID of the asyncReadOp to which the callback was assigned Assert.Equal(readOpId, asyncReadOp.Id); // asyncReadOp.Status must be 'Started' for an asyncReadOp in progress Assert.Equal(AsyncStatus.Started, asyncReadOp.Status); // bytesCompleted must be in range [0, maxBytesToRead] asyncReadOp in progress Assert.InRange(bytesCompleted, 0u, (uint)TestStreamProvider.ModelStreamLength); }; readOp.Completed = (asyncReadOp, passedStatus) => { try { completedCallbackInvoked = true; // asyncReadOp.Id in a completion callback must match the ID of the asyncReadOp to which the callback was assigned Assert.Equal(readOpId, asyncReadOp.Id); // asyncReadOp.Status must match passedStatus for a completed asyncReadOp Assert.Equal(passedStatus, asyncReadOp.Status); // asyncReadOp.Status must be 'Completed' for a completed asyncReadOp Assert.Equal(AsyncStatus.Completed, asyncReadOp.Status); IBuffer resultBuffer = asyncReadOp.GetResults(); // asyncReadOp.GetResults() must not return null for a completed asyncReadOp Assert.NotNull(resultBuffer); AssertExtensions.GreaterThan(resultBuffer.Capacity, 0u, "resultBuffer.Capacity should be more than zero in completed callback"); AssertExtensions.GreaterThan(resultBuffer.Length, 0u, "resultBuffer.Length should be more than zero in completed callback"); AssertExtensions.LessThanOrEqualTo(resultBuffer.Length, resultBuffer.Capacity, "resultBuffer.Length should be <= Capacity in completed callback"); if (inputStreamOptions == InputStreamOptions.None) { // resultBuffer.Length must be equal to requested number of bytes when an asyncReadOp with // InputStreamOptions.None completes successfully Assert.Equal(resultBuffer.Length, (uint)TestStreamProvider.ModelStreamLength); } if (inputStreamOptions == InputStreamOptions.Partial) { AssertExtensions.LessThanOrEqualTo(resultBuffer.Length, (uint)TestStreamProvider.ModelStreamLength, "resultBuffer.Length must be <= requested number of bytes with InputStreamOptions.Partial in completed callback"); } buffer = resultBuffer; } finally { waitHandle.Set(); } }; // Now, let's block until the read op is complete. // We speculate that it will complete within 3500 msec, although under high load it may not be. // If the test fails we should use a better way to determine if callback is really not invoked, or if it's just too slow. waitHandle.WaitOne(500); waitHandle.WaitOne(1000); waitHandle.WaitOne(2000); if (mustInvokeProgressHandler) { Assert.True(progressCallbackInvoked, "Progress callback specified to ReadAsync callback must be invoked when reading from this kind of stream"); } Assert.True(completedCallbackInvoked, "Completion callback specified to ReadAsync callback must be invoked"); // readOp.Status must be 'Completed' for a completed async readOp Assert.Equal(AsyncStatus.Completed, readOp.Status); AssertExtensions.GreaterThan(buffer.Capacity, 0u, "buffer.Capacity should be greater than zero bytes"); AssertExtensions.GreaterThan(buffer.Length, 0u, "buffer.Length should be greater than zero bytes"); AssertExtensions.LessThanOrEqualTo(buffer.Length, buffer.Capacity, "buffer.Length <= buffer.Capacity is required for a completed async readOp"); if (inputStreamOptions == InputStreamOptions.None) { // buffer.Length must be equal to requested number of bytes when an async readOp with // InputStreamOptions.None completes successfully Assert.Equal((uint)TestStreamProvider.ModelStreamLength, buffer.Length); } if (inputStreamOptions == InputStreamOptions.Partial) { AssertExtensions.LessThanOrEqualTo(buffer.Length, (uint)TestStreamProvider.ModelStreamLength, "resultBuffer.Length must be <= requested number of bytes with InputStreamOptions.Partial"); } byte[] results = new byte[buffer.Length]; buffer.CopyTo(0, results, 0, (int)buffer.Length); Assert.True(TestStreamProvider.CheckContent(results, 0, (int)buffer.Length), "Result data returned from AsyncRead must be the same as expected from the test data source"); }
} // ReadAsync_MemoryStream internal static IAsyncOperationWithProgress <IBuffer, uint> ReadAsync_AbstractStream(Stream stream, IBuffer buffer, uint count, InputStreamOptions options) { Debug.Assert(stream != null); Debug.Assert(stream.CanRead); Debug.Assert(buffer != null); Debug.Assert(0 <= count); Debug.Assert(count <= int.MaxValue); Debug.Assert(count <= buffer.Capacity); Debug.Assert(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead); int bytesrequested = (int)count; // Check if the buffer is our implementation. // IF YES: In that case, we can read directly into its data array. // IF NO: The buffer is of unknown implementation. It's not backed by a managed array, but the wrapped stream can only // read into a managed array. If we used the user-supplied buffer we would need to copy data into it after every read. // The spec allows to return a buffer instance that is not the same as passed by the user. So, we will create an own // buffer instance, read data *directly* into the array backing it and then return it to the user. // Note: the allocation costs we are paying for the new buffer are unavoidable anyway, as we would need to create // an array to read into either way. IBuffer dataBuffer = buffer as WindowsRuntimeBuffer; if (dataBuffer == null) { dataBuffer = WindowsRuntimeBuffer.Create((int)Math.Min((uint)int.MaxValue, buffer.Capacity)); } // This operation delegate will we run inside of the returned IAsyncOperationWithProgress: Func <CancellationToken, IProgress <uint>, Task <IBuffer> > readOperation = async(cancelToken, progressListener) => { // No bytes read yet: dataBuffer.Length = 0; // Get the buffer backing array: byte[] data; int offset; bool managedBufferAssert = dataBuffer.TryGetUnderlyingData(out data, out offset); Debug.Assert(managedBufferAssert); // Init tracking values: bool done = cancelToken.IsCancellationRequested; int bytesCompleted = 0; // Loop until EOS, cancelled or read enough data according to options: while (!done) { int bytesread = 0; try { // Read asynchronously: bytesread = await stream.ReadAsync(data !, offset + bytesCompleted, bytesrequested - bytesCompleted, cancelToken) .ConfigureAwait(continueOnCapturedContext: false); // We will continue here on a different thread when read async completed: bytesCompleted += bytesread; // We will handle a cancelation exception and re-throw all others: } catch (OperationCanceledException) { // We assume that cancelToken.IsCancellationRequested is has been set and simply proceed. // (we check cancelToken.IsCancellationRequested later) Debug.Assert(cancelToken.IsCancellationRequested); // This is because if the cancellation came after we read some bytes we want to return the results we got instead // of an empty cancelled task, so if we have not yet read anything at all, then we can throw cancellation: if (bytesCompleted == 0 && bytesread == 0) { throw; } } // Update target buffer: dataBuffer.Length = (uint)bytesCompleted; Debug.Assert(bytesCompleted <= bytesrequested); // Check if we are done: done = options == InputStreamOptions.Partial || // If no complete read was requested, any amount of data is OK bytesread == 0 || // this implies EndOfStream bytesCompleted == bytesrequested || // read all requested bytes cancelToken.IsCancellationRequested; // operation was cancelled // Call user Progress handler: if (progressListener != null) { progressListener.Report(dataBuffer.Length); } } // while (!done) // If we got here, then no error was detected. Return the results buffer: return(dataBuffer); }; // readOperation return(AsyncInfo.Run <IBuffer, uint>(readOperation)); } // ReadAsync_AbstractStream
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { var inputStream = this.GetInputStreamAt(0); return(inputStream.ReadAsync(buffer, count, options)); }
public IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return _randomAccessStream.ReadAsync(buffer, count, options); }
IAsyncOperationWithProgress <IBuffer, uint> IInputStream.ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { #if true return(AsyncInfo.Run(async delegate(CancellationToken cancel, IProgress <uint> progress) { cancel.ThrowIfCancellationRequested(); buffer.Length = Read(buffer, buffer.Length, count); progress.Report(buffer.Length); return buffer; })); #else return(AsyncInfo.Run((CancellationToken cancel, IProgress <uint> progress) => { var task = new Task <IBuffer>(() => { cancel.ThrowIfCancellationRequested(); buffer.Length = Read(buffer, buffer.Length, count); progress.Report(buffer.Length); return buffer; }, cancel); task.Start(); return task; })); #endif }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { //try //{ // return _inputStream.ReadAsync(buffer, count, options); //} //catch (OperationCanceledException) //{ // return AsyncInfo.Run<IBuffer, uint>((token, progress) => new byte[count].AsBuffer()) //} return(AsyncInfo.Run <IBuffer, uint>(async(token, progress) => { Debug.WriteLine($"Read {count} bytes"); try { var result = await _inputStream.ReadAsync(buffer, count, options); progress.Report(buffer.Length); return result; } catch (OperationCanceledException) { progress.Report(count); var noise = new byte[count]; _rand.NextBytes(noise); return noise.AsBuffer(); } catch (Exception e) { throw; } })); }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { BufferWriteEventArgs arg = new BufferWriteEventArgs(BufferActions.Read, _position, count); OnReadCalled?.Invoke(this, ref arg); var t = new Task <IBuffer>(() => { var d = _virtualStream.ReadAsync(buffer, count, options); while (d.Status != AsyncStatus.Completed) { ; } return(buffer); }); t.RunSynchronously(); Func <CancellationToken, IProgress <uint>, Task <IBuffer> > tp = (token, progress) => t; return(AsyncInfo.Run(tp)); }
public IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { lock (stream) { bytesRead += (int)count; } return stream.ReadAsync(buffer, count, options); }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(AsyncInfo.Run <IBuffer, uint>(async(token, progress) => { progress.Report(0); bool fReading; do { lock (this.locker) { fReading = this.readPosition < (this.currentPosition + count) && this.currentPosition + (ulong)count < (ulong)this.contentLength; } if (fReading) { if (token.IsCancellationRequested) { return buffer; } await Task.Delay(10, token); } }while (fReading && this.readTask != null); if (this.data != null) { int length = (int)Math.Min(count, this.contentLength - (int)this.currentPosition); this.data.CopyTo((int)this.currentPosition, buffer, 0, length); buffer.Length = (uint)length; } return buffer; })); }
public Windows.Foundation.IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return AsyncInfo.Run<IBuffer, uint>(async (token, progress) => { byte[] b = new byte[count]; Array.Copy(m_Bytes, m_Position, b,0, b.Length); progress.Report(100); return b.AsBuffer(); }); }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(AsyncInfo.Run <IBuffer, uint>(async(cancellationToken, progress) => { progress.Report(0); if (_stream == null) { var netStream = await _downloader(_requestedPosition, null); _stream = netStream.AsInputStream(); } var result = await _stream.ReadAsync(buffer, count, options).AsTask(cancellationToken, progress); return result; })); }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(AsyncInfo.Run <IBuffer, uint>(async(token, progress) => { return await Task.Run(() => { try { progress.Report(0); var bytes = new byte[buffer.Capacity]; var length = 0; while (true) { if (token.IsCancellationRequested) { break; } var r = _source.Read(bytes, length, (int)count); length += r; if (length == count) { break; } if (r < 1) { break; } } return bytes.AsBuffer(); } finally { progress.Report(100); } }, token); })); }
/// <summary> /// Returns an asynchronous byte reader object. /// </summary> /// <param name="buffer">The buffer into which the asynchronous read operation places the bytes that are read.</param> /// <param name="count">The number of bytes to read that is less than or equal to the <c>Capacity</c> value.</param> /// <param name="options">Specifies the type of the asynchronous read operation.</param> /// <returns>The asynchronous operation.</returns> public IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return this.originalStreamAsInputStream.ReadAsync(buffer, count, options); }
public Windows.Foundation.IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(AsyncInfo.Run <IBuffer, uint>(async(token, progress) => { byte[] b = new byte[count]; Array.Copy(m_Bytes, m_Position, b, 0, b.Length); progress.Report(100); return b.AsBuffer(); })); }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(AsyncInfo.Run <IBuffer, uint>(async(cancellationToken, progress) => { if (length - position < count) { count = length - position; } byte[] data = new byte[count]; for (uint i = 0; i < count; i++) { data[i] = 64; } // Introduce a 1 second delay. await Task.Delay(1000); position += count; progress.Report(count); return data.AsBuffer(); })); }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(AsyncInfo.Run <IBuffer, uint>((token, progress) => { IBuffer buff = new byte[0].AsBuffer(); if (indexCounter < _byteStreamParts.Count()) { buff = _byteStreamParts.ElementAt(indexCounter).AsBuffer(); } indexCounter++; return Task.FromResult(buff); })); }
IAsyncOperationWithProgress<IBuffer, uint> IInputStream.ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return this.GetInputStreamAt(this.Position).ReadAsync(buffer, count, options); }
public Windows.Foundation.IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return GetInputStreamAt(Position).ReadAsync(buffer, count, options); }
public Windows.Foundation.IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { if (Icy_Metaint == 0) //title streaming is disabled { _pos += count; return underlayingSocket.InputStream.ReadAsync(buffer, count, InputStreamOptions.None); } else { if ((ulong)Icy_Metaint > _metapos + count) { _pos += count; return underlayingSocket.InputStream.ReadAsync(buffer, count, options); } else { #region try to handle stream and extract title for (int i = 0; i < bytesToSkip; i++) { underlayingStream.ReadByte(); _pos += (uint)i; } bytesToSkip = 0; var x = (int)count; var amountLeft = (ulong)Icy_Metaint - _metapos; _pos += (uint)Icy_Metaint; _metapos = 0; var amountLeftInt = (uint)amountLeft; int metalength = 0; //underlayingStream.ReadByte(); var data = underlayingSocket.InputStream.ReadAsync(new Windows.Storage.Streams.Buffer((uint)Icy_Metaint), (uint)Icy_Metaint, InputStreamOptions.None); if (metalength != 0) { //ParseTitle(); //var calc = (uint)Icy_Metaint - (uint)MetaDataTagLength + 1; //_pos += calc; //return underlayingSocket.InputStream.ReadAsync( // new Windows.Storage.Streams.Buffer(calc), // calc, InputStreamOptions.None); } return data; #endregion } } return null; }
public Windows.Foundation.IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return AsyncInfo.Run<IBuffer, uint>(async (cancellationToken, progress) => { progress.Report(0); try { if (inputStream == null) { await SendRequesAsync().ConfigureAwait(false); } } catch (Exception ex) { Debug.WriteLine(ex); throw; } IBuffer result = await inputStream.ReadAsync(buffer, count, options).AsTask(cancellationToken, progress).ConfigureAwait(false); // Move position forward. requestedPosition += result.Length; Debug.WriteLine("requestedPosition = {0:N0}", requestedPosition); return result; }); }
/// <summary> /// Read back some number of bytes from our byte array into the buffer. /// </summary> /// <param name="buffer"></param> /// <param name="count"></param> /// <param name="options"></param> /// <returns></returns> public Windows.Foundation.IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(AsyncInfo.Run <IBuffer, uint>(async(token, progress) => { return await Task.Factory.StartNew(() => { lock (this) { var goodCount = (int)Math.Min(DistTillEnd(), (ulong)count); if (goodCount == 0) { return null; } using (var dw = new DataWriter()) { var b = _buffer.AsBuffer((int)_position, goodCount); dw.WriteBuffer(b); var result = dw.DetachBuffer(); _position += (ulong)goodCount; return result; } } }); })); }
IAsyncOperationWithProgress <IBuffer, uint> IInputStream.ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(AsyncInfo.Run <IBuffer, uint>(async(token, progress) => { await _inputStream.ReadAsync(buffer, count, options); progress.Report(50); // Decrypt var bufferBytes = buffer.ToArray(); for (int i = 0; i < bufferBytes.Length; i++) { bufferBytes[i] ^= _key[_position % _key.Length]; _position++; } // progress.Report(100); return bufferBytes.AsBuffer(); })); }
public Windows.Foundation.IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(AsyncInfo.Run <IBuffer, uint>(async(cancellationToken, progress) => { progress.Report(0); try { if (inputStream == null) { await SendRequesAsync().ConfigureAwait(false); } } catch (Exception ex) { Debug.WriteLine(ex); throw; } IBuffer result = await inputStream.ReadAsync(buffer, count, options).AsTask(cancellationToken, progress).ConfigureAwait(false); // Move position forward. requestedPosition += result.Length; Debug.WriteLine("requestedPosition = {0:N0}", requestedPosition); return result; })); }
public Windows.Foundation.IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(System.Runtime.InteropServices.WindowsRuntime.AsyncInfo.Run <IBuffer, uint>((token, progress) => { return System.Threading.Tasks.Task.Run(async() => { uint len = 0; bool result = false; if (internalStream != null) { System.Diagnostics.Debug.WriteLine("ReadAsync request - count: " + count.ToString() + " bytes at " + ReadDataIndex.ToString() + " - Stream Size: " + internalStream.Size + " Stream position: " + internalStream.Position + " Track size: " + GetLength().ToString()); if (ReadDataIndex + count > internalStream.Size) { // Fill the buffer result = await FillInternalStream(ReadDataIndex + count); if (result != true) { System.ArgumentNullException ex = new System.ArgumentNullException("Exception while reading CD Track"); throw ex; } } if (internalStream != null) { var inputStream = internalStream.GetInputStreamAt(ReadDataIndex); if (inputStream != null) { inputStream.ReadAsync(buffer, count, options).AsTask().Wait(); len = buffer.Length; ReadDataIndex += len; System.Diagnostics.Debug.WriteLine("ReadAsync return : " + buffer.Length.ToString() + " bytes at " + (ReadDataIndex - len).ToString() + " - Stream Size: " + internalStream.Size + " Stream position: " + internalStream.Position + " Track size: " + GetLength().ToString()); } } } progress.Report(len); return buffer; }); })); }
public virtual Windows.Foundation.IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { try { StreamAccessLock.Wait(); if (_IsDisposed) { return(AsyncInfo.Run <IBuffer, uint>((token, progress) => { return Task.FromResult(buffer); })); } _CurrentPosition += count; return(_InputStream.ReadAsync(buffer, count, options)); } finally { StreamAccessLock.Release(); } }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { lock (stream) { bytesRead += (int)count; } return(stream.ReadAsync(buffer, count, options)); }
/// <summary> /// Returns an asynchronous byte reader object. /// </summary> /// <param name="buffer">The buffer into which the asynchronous read operation places the bytes that are read.</param> /// <param name="count">The number of bytes to read.</param> /// <param name="options">Specifies the type of the asynchronous read operation.</param> /// <returns>The asynchronous operation. </returns> public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { throw new NotSupportedException(); }
public IAsyncOperationWithProgress <IBuffer, UInt32> ReadAsync(IBuffer buffer, UInt32 count, InputStreamOptions options) { if (buffer == null) { // Mapped to E_POINTER. throw new ArgumentNullException(nameof(buffer)); } if (count < 0 || Int32.MaxValue < count) { ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(count)); ex.SetErrorCode(HResults.E_INVALIDARG); throw ex; } if (buffer.Capacity < count) { ArgumentException ex = new ArgumentException(SR.Argument_InsufficientBufferCapacity); ex.SetErrorCode(HResults.E_INVALIDARG); throw ex; } if (!(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead)) { ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_InvalidInputStreamOptionsEnumValue); ex.SetErrorCode(HResults.E_INVALIDARG); throw ex; } // Commented due to a reported CCRewrite bug. Should uncomment when fixed: //Contract.Ensures(Contract.Result<IAsyncOperationWithProgress<IBuffer, UInt32>>() != null); //Contract.EndContractBlock(); Stream str = EnsureNotDisposed(); IAsyncOperationWithProgress <IBuffer, UInt32> readAsyncOperation; switch (_readOptimization) { case StreamReadOperationOptimization.MemoryStream: readAsyncOperation = StreamOperationsImplementation.ReadAsync_MemoryStream(str, buffer, count); break; case StreamReadOperationOptimization.AbstractStream: readAsyncOperation = StreamOperationsImplementation.ReadAsync_AbstractStream(str, buffer, count, options); break; // Use this pattern to add more optimisation options if necessary: //case StreamReadOperationOptimization.XxxxStream: // readAsyncOperation = StreamOperationsImplementation.ReadAsync_XxxxStream(str, buffer, count, options); // break; default: Debug.Assert(false, "We should never get here. Someone forgot to handle an input stream optimisation option."); readAsyncOperation = null; break; } return(readAsyncOperation); }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(AsyncInfo.Run((Func <System.Threading.CancellationToken, IProgress <uint>, Task <IBuffer> >)(async(cancellationToken, progress) => { progress.Report(0); try { if (_inputStream == null) { await SendRequestAsync().ConfigureAwait(false); } } catch (Exception ex) { Debug.WriteLine(ex); throw; } IBuffer result = await _inputStream.ReadAsync(buffer, count, options).AsTask(cancellationToken, progress).ConfigureAwait(false); Position += result.Length; Debug.WriteLine("requestedPosition = {0:N0}", Position); return result; }))); }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) => new AsyncOperationWithProgress <IBuffer, uint>(async(ct, op) =>
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { Debug.WriteLine("WebRandomAccessStream.ReadAsync:" + pos + "|" + (pos + count) + "|" + Size); pos += count; return(Stream.ReadAsync(buffer, count, options)); }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(AsyncInfo.Run <IBuffer, uint>((token, progress) => Task.Run(async delegate() { var bytesRead = 0u; //keep going until we've read all data. while (bytesRead < count && !token.IsCancellationRequested) { var firstKey = string.Empty; while (string.IsNullOrEmpty(firstKey) && !token.IsCancellationRequested) { //while we don't have data in the trunk, wait for it. firstKey = _internalBuffer.Keys.FirstOrDefault(); await Task.Delay(100, token); } //did we cancel? exit out. if (token.IsCancellationRequested) { return buffer; } //copy the data over. var bufferData = _internalBuffer[firstKey]; var amount = Math.Min(bufferData.Length, count - bytesRead); bufferData.CopyTo(0, buffer, bytesRead, (int)amount); //increment bytes read. bytesRead += (uint)amount; //report the progress. progress.Report(bytesRead); } return buffer; }, token))); }
public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(_stream.ReadAsync(buffer, count, options)); }
public Windows.Foundation.IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(System.Runtime.InteropServices.WindowsRuntime.AsyncInfo.Run <IBuffer, uint>((token, progress) => { return Task.Run(() => { System.Diagnostics.Debug.WriteLine("ReadAsync for: " + count.ToString() + " bytes - Stream Size: " + internalStream.Size + " Stream position: " + internalStream.Position); // If first Read call if ((ReadDataIndex == 0) && (internalStream.Size > count)) { // First dummy read of the header inputStream = internalStream.GetInputStreamAt(wavHeaderLength); uint currentDataLength = (uint)(internalStream.Size - wavHeaderLength); if (currentDataLength > 0) { data.length = currentDataLength; var WAVHeaderBuffer = CreateWAVHeaderBuffer(data.length); if (WAVHeaderBuffer != null) { int headerLen = WAVHeaderBuffer.Length; if (count >= headerLen) { byte[] updatedBuffer = new byte[count]; WAVHeaderBuffer.CopyTo(updatedBuffer.AsBuffer()); if (count > headerLen) { //fill buffer inputStream.ReadAsync(updatedBuffer.AsBuffer((int)headerLen, (int)(count - headerLen)), (uint)(count - headerLen), options).AsTask().Wait(); } buffer = updatedBuffer.AsBuffer(); ReadDataIndex += buffer.Length; System.Diagnostics.Debug.WriteLine("ReadAsync return : " + buffer.Length.ToString() + " bytes - Stream Size: " + internalStream.Size + " Stream position: " + internalStream.Position); progress.Report((uint)buffer.Length); return updatedBuffer.AsBuffer(); } } } } else { inputStream.ReadAsync(buffer, count, options).AsTask().Wait(); ReadDataIndex += buffer.Length; System.Diagnostics.Debug.WriteLine("ReadAsync return : " + buffer.Length.ToString() + " bytes - Stream Size: " + internalStream.Size + " Stream position: " + internalStream.Position); progress.Report((uint)buffer.Length); return buffer; } return null; }); })); }
public Windows.Foundation.IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { var inputStream = GetInputStreamAt(0); return inputStream.ReadAsync(buffer, count, options); }
public Windows.Foundation.IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(GetInputStreamAt(Position).ReadAsync(buffer, count, options)); }
public IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return null; }
IAsyncOperationWithProgress <IBuffer, uint> IInputStream.ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { byte[] dataBytes = ReadInternal((int)count); var ibuffer = dataBytes.AsBuffer(); return(AsyncInfo.Run( delegate(CancellationToken cancellationToken, IProgress <uint> progress) { return Task.FromResult <IBuffer>(ibuffer); })); }
/// <summary> /// Returns an asynchronous byte reader object. /// </summary> /// <param name="buffer">The buffer into which the asynchronous read operation places the bytes that are read.</param> /// <param name="count">The number of bytes to read that is less than or equal to the Capacity value.</param> /// <param name="options">Specifies the type of the asynchronous read operation.</param> /// <returns> /// The asynchronous operation. /// </returns> public IAsyncOperationWithProgress<IBuffer, uint> ReadAsync( IBuffer buffer, uint count, InputStreamOptions options) { return AsyncInfo.Run<IBuffer, uint>((token, progress) => ReadPrivateAsync(progress, buffer, count, options)); }
/// <summary> /// Returns an asynchronous byte reader object. /// </summary> /// <param name="buffer">The buffer into which the asynchronous read operation places the bytes that are read.</param> /// <param name="count">The number of bytes to read that is less than or equal to the Capacity value.</param> /// <param name="options">Specifies the type of the asynchronous read operation.</param> /// <returns>The asynchronous operation.</returns> public IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return ThreadPool.RunAsyncWithProgress<IBuffer, uint>(p => { var data = new byte[count]; this.baseStream.Read(data, 0, (int)count); return data.AsBuffer(); }); }
public IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync(IBuffer buffer, UInt32 count, InputStreamOptions options) { if (buffer == null) { // Mapped to E_POINTER. throw new ArgumentNullException("buffer"); } if (count < 0 || Int32.MaxValue < count) { ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException("count"); ex.SetErrorCode(HResults.E_INVALIDARG); throw ex; } if (buffer.Capacity < count) { ArgumentException ex = new ArgumentException(SR.Argument_InsufficientBufferCapacity); ex.SetErrorCode(HResults.E_INVALIDARG); throw ex; } if (!(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead)) { ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException("options", SR.ArgumentOutOfRange_InvalidInputStreamOptionsEnumValue); ex.SetErrorCode(HResults.E_INVALIDARG); throw ex; } // Commented due to a reported CCRewrite bug. Should uncomment when fixed: //Contract.Ensures(Contract.Result<IAsyncOperationWithProgress<IBuffer, UInt32>>() != null); //Contract.EndContractBlock(); Stream str = EnsureNotDisposed(); IAsyncOperationWithProgress<IBuffer, UInt32> readAsyncOperation; switch (_readOptimization) { case StreamReadOperationOptimization.MemoryStream: readAsyncOperation = StreamOperationsImplementation.ReadAsync_MemoryStream(str, buffer, count); break; case StreamReadOperationOptimization.AbstractStream: readAsyncOperation = StreamOperationsImplementation.ReadAsync_AbstractStream(str, buffer, count, options); break; // Use this pattern to add more optimisation options if necessary: //case StreamReadOperationOptimization.XxxxStream: // readAsyncOperation = StreamOperationsImplementation.ReadAsync_XxxxStream(str, buffer, count, options); // break; default: Debug.Assert(false, "We should never get here. Someone forgot to handle an input stream optimisation option."); readAsyncOperation = null; break; } return readAsyncOperation; }
IAsyncOperationWithProgress <IBuffer, uint> IInputStream.ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) { return(this.GetInputStreamAt(this.Position).ReadAsync(buffer, count, options)); }
public IAsyncOperationWithProgress<IBuffer, uint> ReadAsync (IBuffer buffer, uint count, InputStreamOptions options) { throw new NotImplementedException(); }
} // ReadAsync_MemoryStream internal static IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync_AbstractStream(Stream stream, IBuffer buffer, UInt32 count, InputStreamOptions options) { Debug.Assert(stream != null); Debug.Assert(stream.CanRead); Debug.Assert(buffer != null); Debug.Assert(buffer is IBufferByteAccess); Debug.Assert(0 <= count); Debug.Assert(count <= Int32.MaxValue); Debug.Assert(count <= buffer.Capacity); Debug.Assert(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead); Contract.EndContractBlock(); Int32 bytesRequested = (Int32)count; // Check if the buffer is our implementation. // IF YES: In that case, we can read directly into its data array. // IF NO: The buffer is of unknown implementation. It's not backed by a managed array, but the wrapped stream can only // read into a managed array. If we used the user-supplied buffer we would need to copy data into it after every read. // The spec allows to return a buffer instance that is not the same as passed by the user. So, we will create an own // buffer instance, read data *directly* into the array backing it and then return it to the user. // Note: the allocation costs we are paying for the new buffer are unavoidable anyway, as we we would need to create // an array to read into either way. IBuffer dataBuffer = buffer as WindowsRuntimeBuffer; if (dataBuffer == null) dataBuffer = WindowsRuntimeBuffer.Create((Int32)Math.Min((UInt32)Int32.MaxValue, buffer.Capacity)); // This operation delegate will we run inside of the returned IAsyncOperationWithProgress: Func<CancellationToken, IProgress<UInt32>, Task<IBuffer>> readOperation = async (cancelToken, progressListener) => { // No bytes read yet: dataBuffer.Length = 0; // Get the buffer backing array: Byte[] data; Int32 offset; bool managedBufferAssert = dataBuffer.TryGetUnderlyingData(out data, out offset); Debug.Assert(managedBufferAssert); // Init tracking values: bool done = cancelToken.IsCancellationRequested; Int32 bytesCompleted = 0; // Loop until EOS, cancelled or read enough data according to options: while (!done) { Int32 bytesRead = 0; try { // Read asynchronously: bytesRead = await stream.ReadAsync(data, offset + bytesCompleted, bytesRequested - bytesCompleted, cancelToken) .ConfigureAwait(continueOnCapturedContext: false); // We will continue here on a different thread when read async completed: bytesCompleted += bytesRead; // We will handle a cancelation exception and re-throw all others: } catch (OperationCanceledException) { // We assume that cancelToken.IsCancellationRequested is has been set and simply proceed. // (we check cancelToken.IsCancellationRequested later) Debug.Assert(cancelToken.IsCancellationRequested); // This is because if the cancellation came after we read some bytes we want to return the results we got instead // of an empty cancelled task, so if we have not yet read anything at all, then we can throw cancellation: if (bytesCompleted == 0 && bytesRead == 0) throw; } // Update target buffer: dataBuffer.Length = (UInt32)bytesCompleted; Debug.Assert(bytesCompleted <= bytesRequested); // Check if we are done: done = options == InputStreamOptions.Partial // If no complete read was requested, any amount of data is OK || bytesRead == 0 // this implies EndOfStream || bytesCompleted == bytesRequested // read all requested bytes || cancelToken.IsCancellationRequested; // operation was cancelled // Call user Progress handler: if (progressListener != null) progressListener.Report(dataBuffer.Length); } // while (!done) // If we got here, then no error was detected. Return the results buffer: return dataBuffer; }; // readOperation return AsyncInfo.Run<IBuffer, UInt32>(readOperation); } // ReadAsync_AbstractStream