public static WaitHandle AsyncCopy(this Stream src, Stream dst) { var evt = new ManualResetEvent(false); var buffer = new byte[BUFFER_SIZE]; AsyncCallback cbk = null; cbk = (asyncReadResult) => { int bytesRead = src.EndRead(asyncReadResult); if (bytesRead > 0) { //Console.Write("r"); dst.BeginWrite(buffer, 0, bytesRead, (asyncWriteResult) => { //Console.Write("w"); dst.EndWrite(asyncWriteResult); src.BeginRead(buffer, 0, buffer.Length, cbk, null); }, null); } else { Console.WriteLine(); dst.Flush(); dst.Position = 0; evt.Set(); } }; src.BeginRead(buffer, 0, buffer.Length, cbk, buffer); return evt; }
public static Task<byte[]> ReadBuffer(this Stream stream) { var completionSource = new TaskCompletionSource<byte[]>(); const int defaultBufferSize = 1024 * 16; var buffer = new byte[defaultBufferSize]; var list = new List<byte>(); AsyncCallback callback = null; callback = ar => { int read; try { read = stream.EndRead(ar); } catch (Exception e) { completionSource.SetException(e); return; } list.AddRange(buffer.Take(read)); if (read == 0) { completionSource.SetResult(list.ToArray()); return; } stream.BeginRead(buffer, 0, buffer.Length, callback, null); }; stream.BeginRead(buffer, 0, buffer.Length, callback, null); return completionSource.Task; }
// http://stackoverflow.com/questions/1540658/net-asynchronous-stream-read-write public static void CopyTo(this Stream input, Stream output, int bufferSize) { if (!input.CanRead) throw new InvalidOperationException("input must be open for reading"); if (!output.CanWrite) throw new InvalidOperationException("output must be open for writing"); byte[][] buf = { new byte[bufferSize], new byte[bufferSize] }; int[] bufl = { 0, 0 }; int bufno = 0; IAsyncResult read = input.BeginRead(buf[bufno], 0, buf[bufno].Length, null, null); IAsyncResult write = null; while (true) { // wait for the read operation to complete read.AsyncWaitHandle.WaitOne(); bufl[bufno] = input.EndRead(read); // if zero bytes read, the copy is complete if (bufl[bufno] == 0) { break; } // wait for the in-flight write operation, if one exists, to complete // the only time one won't exist is after the very first read operation completes if (write != null) { write.AsyncWaitHandle.WaitOne(); output.EndWrite(write); } // start the new write operation write = output.BeginWrite(buf[bufno], 0, bufl[bufno], null, null); // toggle the current, in-use buffer // and start the read operation on the new buffer bufno = (bufno == 0 ? 1 : 0); read = input.BeginRead(buf[bufno], 0, buf[bufno].Length, null, null); } // wait for the final in-flight write operation, if one exists, to complete // the only time one won't exist is if the input stream is empty. if (write != null) { write.AsyncWaitHandle.WaitOne(); output.EndWrite(write); } output.Flush(); // return to the caller ; return; }
/// <summary> /// Copies the contents between two <see cref="Stream"/> instances in an async fashion. /// </summary> /// <param name="source">The source stream to copy from.</param> /// <param name="destination">The destination stream to copy to.</param> /// <param name="onComplete">Delegate that should be invoked when the operation has completed. Will pass the source, destination and exception (if one was thrown) to the function. Can pass in <see langword="null" />.</param> public static void CopyTo(this Stream source, Stream destination, Action<Stream, Stream, Exception> onComplete) { var buffer = new byte[BufferSize]; Action<Exception> done = e => { if (onComplete != null) { onComplete.Invoke(source, destination, e); } }; AsyncCallback rc = null; rc = readResult => { try { var read = source.EndRead(readResult); if (read <= 0) { done.Invoke(null); return; } destination.BeginWrite(buffer, 0, read, writeResult => { try { destination.EndWrite(writeResult); source.BeginRead(buffer, 0, buffer.Length, rc, null); } catch (Exception ex) { done.Invoke(ex); } }, null); } catch (Exception ex) { done.Invoke(ex); } }; source.BeginRead(buffer, 0, buffer.Length, rc, null); }
public static void QueueRead( this Stream stream, Func<ArraySegment<byte>, Action, bool> callback, Action<Exception> error, Action complete ) { var buffer = new byte[4*1024]; stream.BeginRead( buffer, 0, buffer.Length, x => { var read = 0; try { read = stream.EndRead( x ); } catch (Exception e) { error( e ); } if( read > 0 ) { var waitForCall = callback( new ArraySegment<byte>(buffer, 0, read), () => QueueRead( stream, callback, error, complete ) ); if( !waitForCall ) QueueRead( stream, callback, error, complete ); } else { complete(); } }, null ); }
public static K<string> ReadToEndAsync(this Stream stream) { return respond => { StringBuilder sb = new StringBuilder(); byte[] buffer = new byte[1024]; Func<IAsyncResult> readChunk = null; readChunk = () => stream.BeginRead(buffer, 0, 1024, result => { int read = stream.EndRead(result); if (read > 0) { sb.Append(Encoding.UTF8.GetString(buffer, 0, read)); readChunk(); } else { stream.Dispose(); respond(sb.ToString()); } }, null); readChunk(); }; }
/// <summary> /// 지정된 스트림을 비동기 방식으로 읽어, <paramref name="buffer"/>에 채웁니다. 작업의 결과는 읽은 바이트 수입니다. /// </summary> public static Task<int> ReadAsync(this Stream stream, byte[] buffer, int offset, int count) { if(IsDebugEnabled) log.Debug("비동기 방식으로 스트림을 읽어 버퍼에 씁니다... offset=[{0}], count=[{1}]", offset, count); // Silverlight용 TPL에서는 지원하지 3개 이상의 인자를 지원하지 않는다. var ar = stream.BeginRead(buffer, offset, count, null, null); return Task.Factory.StartNew(() => stream.EndRead(ar)); }
/// <summary> /// Extends BeginRead so that buffer offset of 0 and call to Array.Length are not needed. /// <example> /// isolatedstoragefilestream.BeginRead(buffer, userCallback); /// </example> /// </summary> public static IAsyncResult BeginRead(this IsolatedStorageFileStream isolatedstoragefilestream, Byte[] buffer, AsyncCallback userCallback) { if(isolatedstoragefilestream == null) throw new ArgumentNullException("isolatedstoragefilestream"); if(buffer == null) throw new ArgumentNullException("buffer"); return isolatedstoragefilestream.BeginRead(buffer, 0, buffer.Length, userCallback); }
public static IAsyncResult BeginReadToEnd(this Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { byte[] tempBuffer = new byte[count]; ByteArrayAsyncResult result = new ByteArrayAsyncResult(callback, state, buffer, offset, tempBuffer); ByteArrayAsyncState asyncState = new ByteArrayAsyncState {Result = result, Stream = stream}; stream.BeginRead(tempBuffer, 0, count, OnRead, asyncState); return result; }
public static IObservable<byte[]> ReadBytes(this Stream stream, int count) { var buffer = new byte[count]; return Observable.FromAsyncPattern((cb, state) => stream.BeginRead(buffer, 0, count, cb, state), ar => { stream.EndRead(ar); return buffer; })(); }
/// <summary> /// Extends BeginRead so that buffer offset of 0 and call to Array.Length are not needed. /// <example> /// pipestream.BeginRead(buffer, callback); /// </example> /// </summary> public static IAsyncResult BeginRead(this NamedPipeServerStream pipestream, Byte[] buffer, AsyncCallback callback) { if(pipestream == null) throw new ArgumentNullException("pipestream"); if(buffer == null) throw new ArgumentNullException("buffer"); return pipestream.BeginRead(buffer, 0, buffer.Length, callback); }
/// <summary> /// Extends BeginRead so that buffer offset of 0 and call to Array.Length are not needed. /// <example> /// filestream.BeginRead(array, userCallback); /// </example> /// </summary> public static IAsyncResult BeginRead(this FileStream filestream, Byte[] array, AsyncCallback userCallback) { if(filestream == null) throw new ArgumentNullException("filestream"); if(array == null) throw new ArgumentNullException("array"); return filestream.BeginRead(array, 0, array.Length, userCallback); }
/// <summary> /// Extends BeginRead so that buffer offset of 0 and call to Array.Length are not needed. /// <example> /// gzipstream.BeginRead(array, asyncCallback); /// </example> /// </summary> public static IAsyncResult BeginRead(this GZipStream gzipstream, Byte[] array, AsyncCallback asyncCallback) { if(gzipstream == null) throw new ArgumentNullException("gzipstream"); if(array == null) throw new ArgumentNullException("array"); return gzipstream.BeginRead(array, 0, array.Length, asyncCallback); }
/// <summary> /// Extends BeginRead so that buffer offset of 0 and call to Array.Length are not needed. /// <example> /// stream.BeginRead(buffer, callback); /// </example> /// </summary> public static IAsyncResult BeginRead(this Stream stream, Byte[] buffer, AsyncCallback callback) { if(stream == null) throw new ArgumentNullException("stream"); if(buffer == null) throw new ArgumentNullException("buffer"); return stream.BeginRead(buffer, 0, buffer.Length, callback); }
/// <summary> /// Extends BeginRead so that buffer offset of 0 and call to Array.Length are not needed. /// <example> /// deflatestream.BeginRead(array, asyncCallback); /// </example> /// </summary> public static IAsyncResult BeginRead(this DeflateStream deflatestream, Byte[] array, AsyncCallback asyncCallback) { if(deflatestream == null) throw new ArgumentNullException("deflatestream"); if(array == null) throw new ArgumentNullException("array"); return deflatestream.BeginRead(array, 0, array.Length, asyncCallback); }
public static Task<int> ReadAsync(this Stream stream, byte[] buffer) { try { return Task.Factory.FromAsync((cb, state) => stream.BeginRead(buffer, 0, buffer.Length, cb, state), ar => stream.EndRead(ar), null); } catch (System.Exception ex) { return TaskAsyncHelper.FromError<int>(ex); } }
public static void Read(this Stream stream, byte[] buffer, int offset, int size, Action<int> continuation) { var daemon = Daemons.Current; stream.BeginRead(buffer, offset, size, asyncResult => { int read = stream.EndRead(asyncResult); ((IDaemon) asyncResult.AsyncState).Schedule(() => continuation(read)); }, daemon); }
public static IYield NioRead(this Stream stream, byte[] buffer, int offset, int count) { var waitEvent = new WaitEvent(); var thread = Microthread.CurrentMicrothread; stream.BeginRead(buffer, offset, count, ar => { thread.Result = stream.EndRead(ar); ((WaitEvent)ar.AsyncState).Set(); }, waitEvent); return Microthread.Wait(waitEvent); }
/// <include file='../_Doc/mscorlib.xml' path='doc/members/member[@name="M:System.IO.Stream.BeginRead(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object)"]/*' /> /// <param name="stream">Stream on which to begin reading.</param> public static IAsyncResult BeginRead(this Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback, object state) { #if DOTNET || WINDOWS_PHONE return stream.BeginRead(buffer, offset, count, callback, state); #else return new TaskFactory<int>().StartNew(asyncState => stream.Read(buffer, offset, count), state) .ContinueWith(task => { callback(task); return task.Result; }); #endif }
public static Task<int> ReadAsync( this Stream stream, byte[] buffer, int offset, int size) { var tcs = new TaskCompletionSource<int>(stream); stream.BeginRead(buffer, offset, size, iar => { var t = (TaskCompletionSource<int>)iar.AsyncState; var s = (Stream)t.Task.AsyncState; try { t.TrySetResult(s.EndRead(iar)); } catch (Exception exc) { t.TrySetException(exc); } }, tcs); return tcs.Task; }
public static Task<int> ReadAsync(this Stream stream, byte[] buffer) { #if NETFX_CORE return stream.ReadAsync(buffer, 0, buffer.Length); #else try { return Task.Factory.FromAsync((cb, state) => stream.BeginRead(buffer, 0, buffer.Length, cb, state), ar => stream.EndRead(ar), null); } catch (Exception ex) { return TaskAsyncHelper.FromError<int>(ex); } #endif }
internal static void smethod_0(this NetworkStream networkStream_0, int int_0, Action<NetworkStream, byte[]> action_0, Action<NetworkStream, Exception> action_1) { if (action_0 != null && action_1 != null) { Class25.Class28 @class = new Class25.Class28(); @class.Buffer = new byte[int_0]; @class.CurrentPosition = 0; @class.Stream = networkStream_0; @class.OnSuccess = action_0; @class.OnException = action_1; try { networkStream_0.BeginRead(@class.Buffer, 0, int_0, new AsyncCallback(Class25.smethod_1), @class); return; } catch (Exception arg) { action_1(networkStream_0, arg); return; } } throw new Exception("Callback cannot be null"); }
public static Future<int> AsyncRead (this Stream stream, byte[] buffer, int offset, int count) { #if XBOX return Future.RunInThread(() => stream.Read(buffer, offset, count)); #else var f = new Future<int>(); try { stream.BeginRead(buffer, offset, count, (ar) => { try { int bytesRead; lock (stream) bytesRead = stream.EndRead(ar); f.Complete(bytesRead); } catch (FutureHandlerException) { throw; } catch (Exception ex) { f.Fail(ex); } }, stream); } catch (Exception ex) { f.Fail(ex); } return f; #endif }
internal static Task<int> ReadAsync(this Stream stream, byte[] buffer, int offset, int count) { return new APMTask<int>( (callback, st) => stream.BeginRead(buffer, offset, count, callback, st), stream.EndRead); }
/// <summary> /// Extends BeginRead so that when a state object is not needed, null does not need to be passed. /// <example> /// pipestream.BeginRead(buffer, offset, count, callback); /// </example> /// </summary> public static IAsyncResult BeginRead(this NamedPipeServerStream pipestream, Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback) { if(pipestream == null) throw new ArgumentNullException("pipestream"); return pipestream.BeginRead(buffer, offset, count, callback, null); }
public static void CopyToStreamAsync(this Stream source, Stream destination, Action<Stream, Stream, Exception> completed, Action<uint> progress, uint bufferSize, uint? maximumDownloadSize, TimeSpan? timeout) { byte[] buffer = new byte[bufferSize]; Action<Exception> done = exception => { if (completed != null) { completed(source, destination, exception); } }; int maxDownloadSize = maximumDownloadSize.HasValue ? (int)maximumDownloadSize.Value : int.MaxValue; int bytesDownloaded = 0; IAsyncResult asyncResult = source.BeginRead(buffer, 0, new[] {maxDownloadSize, buffer.Length}.Min(), null, null); Action<IAsyncResult, bool> endRead = null; endRead = (innerAsyncResult, innerIsTimedOut) => { try { int bytesRead = source.EndRead(innerAsyncResult); if(innerIsTimedOut) { done(new TimeoutException()); } int bytesToWrite = new[] { maxDownloadSize - bytesDownloaded, buffer.Length, bytesRead }.Min(); destination.Write(buffer, 0, bytesToWrite); bytesDownloaded += bytesToWrite; if (!progress.IsNull() && bytesToWrite > 0) { progress((uint)bytesDownloaded); } if (bytesToWrite == bytesRead && bytesToWrite > 0) { asyncResult = source.BeginRead(buffer, 0, new[] { maxDownloadSize, buffer.Length }.Min(), null, null); // ReSharper disable PossibleNullReferenceException // ReSharper disable AccessToModifiedClosure asyncResult.FromAsync((ia, isTimeout) => endRead(ia, isTimeout), timeout); // ReSharper restore AccessToModifiedClosure // ReSharper restore PossibleNullReferenceException } else { done(null); } } catch (Exception exc) { done(exc); } }; asyncResult.FromAsync((ia, isTimeout) => endRead(ia, isTimeout), timeout); }
internal static void WriteToSync(this Stream stream, Stream toStream) { int readCount; do { byte[] buffer = new byte[BufferSize]; readCount = stream.EndRead(stream.BeginRead(buffer, 0, buffer.Length, null /* Callback */, null /* State */)); toStream.Write(buffer, 0, readCount); } while (readCount != 0); }
/// <summary> /// Extends BeginRead so that when a state object is not needed, null does not need to be passed. /// <example> /// gzipstream.BeginRead(array, offset, count, asyncCallback); /// </example> /// </summary> public static IAsyncResult BeginRead(this GZipStream gzipstream, Byte[] array, Int32 offset, Int32 count, AsyncCallback asyncCallback) { if(gzipstream == null) throw new ArgumentNullException("gzipstream"); return gzipstream.BeginRead(array, offset, count, asyncCallback, null); }
public static Task<int> ReadAsync(this Stream stream, byte[] buffer) { return Task.Factory.FromAsync((cb, state) => stream.BeginRead(buffer, 0, buffer.Length, cb, state), ar => stream.EndRead(ar), null); }
/// <summary> /// /// </summary> /// <param name="stm"></param> /// <param name="readCallBack"></param> /// <param name="complete"></param> public static void AsyncGetBytes(this Stream stm, Action<byte[]> readCallBack, Action complete) { var buffer = new byte[Chunk]; stm.BeginRead(buffer, 0, Chunk, ReadAsyncCallback, new { Stream = stm, Buffer = buffer, Action = readCallBack, Complete = complete }); }