BeginWrite() private method

private BeginWrite ( byte buffer, int offset, int count, AsyncCallback callback, Object state ) : IAsyncResult
buffer byte
offset int
count int
callback AsyncCallback
state Object
return IAsyncResult
        static IEnumerable<Task> CopyStream(Stream input, Stream output)
        {
            var buffer = new byte[0x2000];

            while (true)
            {
                // Create task to read from the input stream
                var read = Task<int>.Factory.FromAsync((buf, offset, count, callback, state) =>
                                                           {
                                                               Console.WriteLine("Issuing BeginRead");
                                                               return input.BeginRead(buf, offset, count, callback, state);
                                                           },
                                                           ar =>
                                                               {
                                                                   Console.WriteLine("Read completed");
                                                                   return input.EndRead(ar);
                                                               },
                                                               buffer, 0, buffer.Length, null);

                yield return read;

                // If we read no data, return
                if (read.Result == 0) break;

                // Create task to write to the output stream
                yield return Task.Factory.FromAsync((buf, offset, count, callback, state) =>
                                                           {
                                                               Console.WriteLine("Issuing BeginWrite");
                                                               return output.BeginWrite(buf, offset, count, callback, state);
                                                           },
                                                           ar =>
                                                               {
                                                                   Console.WriteLine("Write completed");
                                                                   output.EndWrite(ar);
                                                               }, buffer, 0, read.Result, null);
            }
        }
 private static void WriteToStreamAsync(Stream s)
 {
     var t = Task.Factory.FromAsync(
         (callback, state) => s.BeginWrite(new byte[] { 1, 2, 3 }, 0, 3, callback, state),
         (ar) => s.EndWrite(ar),
         null);
     t.Wait();
 }
Exemplo n.º 3
0
        public override IAsyncResult BeginWrite(byte [] buffer, int offset, int count,
                                                AsyncCallback cback, object state)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(GetType().ToString());
            }

            byte []      bytes   = null;
            MemoryStream ms      = GetHeaders(false);
            bool         chunked = response.SendChunked;

            if (ms != null)
            {
                long start = ms.Position;
                ms.Position = ms.Length;
                if (chunked)
                {
                    bytes = GetChunkSizeBytes(count, false);
                    ms.Write(bytes, 0, bytes.Length);
                }
                ms.Write(buffer, offset, count);
                buffer = ms.GetBuffer();
                offset = (int)start;
                count  = (int)(ms.Position - start);
            }
            else if (chunked)
            {
                bytes = GetChunkSizeBytes(count, false);
                InternalWrite(bytes, 0, bytes.Length);
            }

            return(stream.BeginWrite(buffer, offset, count, cback, state));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Pipes data from one stream to another
        /// </summary>
        /// <param name="input">Stream to read from</param>
        /// <param name="output">Stream to write to</param>
        /// <param name="MaxBufferSize">Size of buffer to use</param>
        /// <returns>Number of bytes piped</returns>
        public static int Pipe(Stream input, Stream output, int MaxBufferSize)
        {
            //Internal buffer are two buffers, each half of allowed buffer size, aligned to 1kb blocks
            int bufferSize = (MaxBufferSize / 2) & ~1023;
            if (bufferSize <= 0) throw new Exception("Specified buffer size to small");

            byte[][] buffer = new byte[2][];
            buffer[0] = new byte[bufferSize];
            buffer[1] = new byte[bufferSize];
            int currentBuffer = 0;

            int r, total=0;
            IAsyncResult asyncRead,asyncWrite;

            //Read first block
            r = input.Read(buffer[currentBuffer], 0, bufferSize);

            //Continue while we're getting data
            while (r > 0)
            {
                //read and write simultaneously
                asyncWrite = output.BeginWrite(buffer[currentBuffer], 0, r, null, null);
                asyncRead = input.BeginRead(buffer[1-currentBuffer], 0, bufferSize, null, null);
                //Wait for both
                output.EndWrite(asyncWrite);
                r = input.EndRead(asyncRead);
                //Switch buffers
                currentBuffer = 1 - currentBuffer;
                //Count bytes
                total += r;
            }

            //Return number of bytes piped
            return total;
        }
        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;
        }
Exemplo n.º 6
0
 public override IAsyncResult BeginWrite(
     byte[] buffer,
     int offset,
     int count,
     AsyncCallback callback,
     object state
     )
 {
     Trace.WriteLine("TraceStream", String.Format("BeginWrite(): offset({0}), count({1})", offset, count));
     return(m_in.BeginWrite(buffer, offset, count, callback, state));
 }
        // 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;
        }
        private static IEnumerable<CompletionPort> CreateFixedVhdFileAtAsync(AsyncMachine machine, Stream destination, long virtualSize)
        {
            var footer = VhdFooterFactory.CreateFixedDiskFooter(virtualSize);
            var serializer = new VhdFooterSerializer(footer);
            var buffer = serializer.ToByteArray();
            destination.SetLength(virtualSize + VhdConstants.VHD_FOOTER_SIZE);
            destination.Seek(-VhdConstants.VHD_FOOTER_SIZE, SeekOrigin.End);

            destination.BeginWrite(buffer, 0, buffer.Length, machine.CompletionCallback, null);
            yield return CompletionPort.SingleOperation;
            destination.EndWrite(machine.CompletionResult);
            destination.Flush();
        }
Exemplo n.º 9
0
        /// <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);
        }
Exemplo n.º 10
0
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            var tcs = new TaskCompletionSource<object>();
            _body.Invoke(
                (data, callback) =>
                {
                    if (data.Count == 0)
                    {
                        stream.Flush();
                    }
                    else if (callback == null)
                    {
                        stream.Write(data.Array, data.Offset, data.Count);
                    }
                    else
                    {
                        var sr = stream.BeginWrite(data.Array, data.Offset, data.Count, ar =>
                        {
                            if (!ar.CompletedSynchronously)
                            {
                                try { stream.EndWrite(ar); }
                                catch { }
                                try { callback.Invoke(); }
                                catch { }
                            }
                        }, null);

                        if (!sr.CompletedSynchronously)
                        {
                            return true;
                        }
                        stream.EndWrite(sr);
                        callback.Invoke();
                    }
                    return false;
                },
                ex =>
                {
                    if (ex == null)
                    {
                        tcs.TrySetResult(null);
                    }
                    else
                    {
                        tcs.TrySetException(ex);
                    }
                },
                _cancellationToken);
            return tcs.Task;
        }
Exemplo n.º 11
0
        public void SendPiece(IO.Stream ostream, int pieceId, int begin, int length, IO.Stream istream, PeerFinishedPieceTransfer callback, object state)
        {
            SendMessageHeader(ostream, PeerMessage.Piece, 8 + length);
            WriteInt(ostream, pieceId);
            WriteInt(ostream, begin);

            byte[] writeData = new byte[length];
            istream.Read(writeData, 0, length);

            object[] objs = new object[4];
            objs[0] = ostream;
            objs[1] = callback;
            objs[2] = state;
            objs[3] = length;

            ostream.BeginWrite(writeData, 0, writeData.Length, new System.AsyncCallback(OnWriteFinished), (object)objs);
        }
Exemplo n.º 12
0
 public override void write(byte[] buffer, int offset, int size,
                            ResultHandler rh)
 {
     if (mResponse != null)
     {
         throw new Exception("HTTP write");
     }
     if (mStream == null)
     {
         mRequest.BeginGetRequestStream(
             new AsyncCallback(delegate(IAsyncResult ar)
         {
             mStream = mRequest.EndGetRequestStream(ar);
             mStream.BeginWrite(buffer, offset, size,
                                new AsyncCallback(WriteCallback), rh);
         }), rh);
         return;
     }
     mStream.BeginWrite(buffer, offset, size,
                        new AsyncCallback(WriteCallback), rh);
 }
Exemplo n.º 13
0
      private static IEnumerator<Int32> CopyStream(AsyncEnumerator<Int64> ae, Stream source, Stream destination, Int32 bufferSize, Action<Int64> reportProgress) {
         Byte[] buffer = new Byte[bufferSize];
         Int64 totalBytesRead = 0;
         while (true) {
            ae.SetOperationTag("Reading from source stream");
            // Read whichever is smaller (number of bytes left to read OR the buffer size)
            source.BeginRead(buffer, 0, buffer.Length, ae.End(), null);
            yield return 1;
            Int32 bytesReadThisTime = source.EndRead(ae.DequeueAsyncResult());
            totalBytesRead += bytesReadThisTime;

            ae.SetOperationTag("Writing to destination stream");
            destination.BeginWrite(buffer, 0, bytesReadThisTime, ae.End(), null);
            yield return 1;
            destination.EndWrite(ae.DequeueAsyncResult());

            if (reportProgress != null) reportProgress(totalBytesRead);
            if (bytesReadThisTime < buffer.Length) break;
         }
         ae.Result = totalBytesRead;
      }
Exemplo n.º 14
0
        public Task Start(Stream stream)
        {
            TaskCompletionSource<object> completed = new TaskCompletionSource<object>();
            var bytes = encoding.GetBytes(text);
            stream.BeginWrite(bytes, 0, bytes.Length,
                async =>
                {
                    try
                    {
                        stream.EndWrite(async);
                        completed.TrySetResult(null);
                    }
                    catch (Exception ex)
                    {
                        completed.TrySetException(ex);
                    }
                },
                null);

            return completed.Task;
        }
Exemplo n.º 15
0
        internal void UpLoadFile(string fullFileName, string uploadedName, string dirName)
        {
            string fileName = uploadedName + new FileInfo(fullFileName).Extension;
            string uri      = string.Format("ftp://{0}:{1}/{2}/{3}", _ip, _port, dirName, fileName);

            _request = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(uri));
            //request.Credentials = new System.Net.NetworkCredential(sftpUsername, sftpPassword);
            _request.KeepAlive = false;
            _request.UseBinary = true;
            _request.Method    = System.Net.WebRequestMethods.Ftp.UploadFile;
            _request.UseBinary = true;
            System.IO.FileStream fs = new System.IO.FileStream(fullFileName, System.IO.FileMode.Open);
            _request.ContentLength = fs.Length;
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            System.IO.Stream stream = _request.GetRequestStream();
            UploadObject     uo     = new UploadObject {
                stream = stream, fs = fs
            };

            stream.BeginWrite(buffer, 0, buffer.Length, UploadCallBack, uo);
        }
Exemplo n.º 16
0
    public static bool VerifyWriteException(System.IO.Stream serialStream, Type expectedException)
    {
        bool retValue = true;

        System.IAsyncResult writeAsyncResult;

        try
        {
            writeAsyncResult = serialStream.BeginWrite(new byte[BYTE_SIZE_EXCEPTION], 0, BYTE_SIZE_EXCEPTION, null, null);
            writeAsyncResult.AsyncWaitHandle.WaitOne();
            Console.WriteLine("ERROR!!!: No Excpetion was thrown");
            retValue = false;
        }
        catch (System.Exception e)
        {
            if (e.GetType() != expectedException)
            {
                Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException);
                retValue = false;
            }
        }
        return(retValue);
    }
        public ProgressWriteAsyncResult(Stream innerStream, ProgressStream progressStream, byte[] buffer, int offset, int count, AsyncCallback callback, object state)
            : base(callback, state)
        {
            Contract.Assert(innerStream != null);
            Contract.Assert(progressStream != null);
            Contract.Assert(buffer != null);

            _innerStream = innerStream;
            _progressStream = progressStream;
            _count = count;

            try
            {
                IAsyncResult result = innerStream.BeginWrite(buffer, offset, count, _writeCompletedCallback, this);
                if (result.CompletedSynchronously)
                {
                    WriteCompleted(result);
                }
            }
            catch (Exception e)
            {
                Complete(true, e);
            }
        }
Exemplo n.º 18
0
 public static void CopyTo(this Stream source, Stream destination, int bufferSize)
 {
     long ts = DateTime.Now.Ticks;
     long cbTotal = 0L;
     byte[] read_buffer = new byte[bufferSize];
     int cb = source.Read(read_buffer, 0, read_buffer.Length);
     AutoResetEvent writeLock = new AutoResetEvent(false);
     while (cb > 0)
     {
         cbTotal += cb;
         try
         {
             byte[] write_buffer = read_buffer;
             destination.BeginWrite(write_buffer, 0, cb, (AsyncCallback)delegate(IAsyncResult ar)
             {
                 try
                 {
                     destination.EndWrite(ar);
                 }
                 finally
                 {
                     writeLock.Set();
                 }
             }, null);
         }
         catch
         {
             writeLock.Set();
             throw;
         }
         read_buffer = new byte[bufferSize];
         cb = source.Read(read_buffer, 0, read_buffer.Length);
         writeLock.WaitOne();
     }
     ts = DateTime.Now.Ticks - ts;
 }
Exemplo n.º 19
0
		static IAsyncResult DoBeginWrite(Stream stream, ManualResetEvent mre, byte[] RandomBuffer)
		{
			return stream.BeginWrite (RandomBuffer, 0, RandomBuffer.Length, ar => {
				stream.EndWrite (ar);

				// we don't supply an ManualResetEvent so this will throw an NRE on the second run
				// which nunit-console will ignore (but other test runners don't like that)
				if (mre == null)
					return;

				DoBeginWrite (stream, null, RandomBuffer).AsyncWaitHandle.WaitOne ();
				mre.Set ();
			}, null);
		}
Exemplo n.º 20
0
        public static void StreamWriteAsync(
            Stream stream,
            byte[] buffer,
            int offset,
            int count,
            SynchronizationContextWrapper syncContext,
            Action<int, Exception> callback)
        {
            Exception error = null;
            int length = 0;

            try
            {
                stream.BeginWrite(buffer, offset, count,
                    delegate(IAsyncResult ar)
                    {
                        try
                        {
                            stream.EndWrite(ar);
                            stream.Flush();
                            length = count;
                        }
                        catch (Exception e)
                        {
                            error = e;
                        }

                        callback(length, error);
                    },
                    null);
            }
            catch (Exception e)
            {
                error = e;
                callback(length, error);
            }
        } 
Exemplo n.º 21
0
		static IAsyncResult DoBeginWrite(Stream stream, ManualResetEvent mre, byte[] RandomBuffer)
		{
			return stream.BeginWrite (RandomBuffer, 0, RandomBuffer.Length, ar => {
				IAsyncResult begin_write_recursive_ares;

				try {
					stream.EndWrite (ar);

					// we don't supply an ManualResetEvent so this will throw an NRE on the second run
					// which nunit-console will ignore (but other test runners don't like that)
					if (mre == null)
						return;

					begin_write_recursive_ares = DoBeginWrite (stream, null, RandomBuffer);
					begin_write_recursive_ares.AsyncWaitHandle.WaitOne ();

					mre.Set ();
				} catch (ObjectDisposedException e) {
					Console.WriteLine ("stream was disposed: {0}", e);
				}
			}, null);
		}
Exemplo n.º 22
0
 public Task WriteToStreamAsync(Stream stream)
 {
     return Task.Factory.FromAsync((Func<AsyncCallback, object, IAsyncResult>) ((callback, state) => stream.BeginWrite(this.buffer, 0, this.storedCount, callback, state)), new Action<IAsyncResult>(stream.EndWrite), null);
 }
Exemplo n.º 23
0
 private CopyItemAction CopyStreamAsync(Stream sourceStream, Stream destStream, IVirtualItem sourceItem, IVirtualItem destItem)
 {
     object obj2;
     lock ((obj2 = this.FSnapshotLock))
     {
         this.FCopyMode = CopyMode.Async;
     }
     if (this.Buffer2 == null)
     {
         this.Buffer2 = new byte[this.Buffer1.Length];
     }
     byte[] buffer = this.Buffer1;
     byte[] buffer2 = this.Buffer2;
     int count = 0;
     ProcessedSize processed = CreateFileProcessed(sourceStream, sourceItem);
     if (!((processed.Total <= buffer.Length) || this.RaiseFileProgress(ref processed)))
     {
         return CopyItemAction.SkipUndoDest;
     }
     IAsyncResult asyncResult = sourceStream.BeginRead(buffer, 0, buffer.Length, null, null);
     do
     {
         count = sourceStream.EndRead(asyncResult);
         if (base.CheckCancellationPending())
         {
             return CopyItemAction.SkipUndoDest;
         }
         IAsyncResult result2 = destStream.BeginWrite(buffer, 0, count, null, null);
         byte[] buffer3 = buffer;
         if (count > 0)
         {
             asyncResult = sourceStream.BeginRead(buffer2, 0, buffer2.Length, null, null);
             buffer2 = Interlocked.Exchange<byte[]>(ref buffer, buffer2);
         }
         try
         {
             destStream.EndWrite(result2);
         }
         catch (IOException exception)
         {
             CopyItemAction action = this.HandleCopyIOException(destItem, sourceItem, destItem, destStream, buffer3, count, exception);
             if (action != CopyItemAction.Next)
             {
                 return action;
             }
         }
         lock ((obj2 = this.FSnapshotLock))
         {
             this.FTotalProcessed.AddProcessedSize((long) count);
         }
         this.RaiseProgress();
         processed.AddProcessedSize((long) count);
         if (!this.RaiseFileProgress(ref processed))
         {
             return CopyItemAction.SkipUndoDest;
         }
     }
     while (count > 0);
     return CopyItemAction.Next;
 }
Exemplo n.º 24
0
        static void Write(Cargo<ArraySegment<byte>> cargo, Stream stream)
        {
            if (!cargo.Delayable) {
                stream.Write(cargo.Result.Array, cargo.Result.Offset, cargo.Result.Count);
                return;
            }

            var result = stream.BeginWrite(cargo.Result.Array, cargo.Result.Offset, cargo.Result.Count, asyncResult => {
                if (asyncResult.CompletedSynchronously)
                    return;
                stream.EndWrite(asyncResult);
                cargo.Resume();
            }, null);

            if (result.CompletedSynchronously)
                stream.EndWrite(result);
            else
                cargo.Delay();
        }
Exemplo n.º 25
0
        /// <summary>
        /// Starts writing response to the specified stream.
        /// </summary>
        /// <param name="session">Owner IMAP session.</param>
        /// <param name="stream">Stream where to store response.</param>
        /// <param name="mailboxEncoding">Specifies how mailbox name is encoded.</param>
        /// <param name="completedAsyncCallback">Callback to be called when this method completes asynchronously.</param>
        /// <returns>Returns true is method completed asynchronously(the completedAsyncCallback is raised upon completion of the operation).
        /// Returns false if operation completed synchronously.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception>
        protected virtual bool ToStreamAsync(IMAP_Session session,Stream stream,IMAP_Mailbox_Encoding mailboxEncoding,EventHandler<EventArgs<Exception>> completedAsyncCallback)
        {
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            string responseS = ToString(mailboxEncoding);
            byte[] response  = Encoding.UTF8.GetBytes(responseS);

            // Log.
            if(session != null){
                session.LogAddWrite(response.Length,responseS.TrimEnd());
            }

            // Starts writing response to stream.
            IAsyncResult ar = stream.BeginWrite(
                response,
                0,
                response.Length,
                delegate(IAsyncResult r){                    
                    if(r.CompletedSynchronously){
                        return;
                    }

                    try{
                        stream.EndWrite(r);

                        if(completedAsyncCallback != null){
                            completedAsyncCallback(this,new EventArgs<Exception>(null));
                        }
                    }
                    catch(Exception x){
                        if(completedAsyncCallback != null){
                            completedAsyncCallback(this,new EventArgs<Exception>(x));
                        }
                    }
                },
                null
            );
            // Completed synchronously, process result.
            if(ar.CompletedSynchronously){
                stream.EndWrite(ar);

                return false;
            }
            // Completed asynchronously, stream.BeginWrite AsyncCallback will continue processing.
            else{
                return true;
            }
        }
Exemplo n.º 26
0
 /// <inheritdoc />
 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
 {
     return(_stream.BeginWrite(buffer, offset, count, callback, state));
 }
Exemplo n.º 27
0
		static IAsyncResult DoBeginWrite(Stream stream, ManualResetEvent mre, byte[] RandomBuffer)
		{
			return stream.BeginWrite (RandomBuffer, 0, RandomBuffer.Length, ar => {
				stream.EndWrite (ar);

				DoBeginWrite (stream, null, RandomBuffer).AsyncWaitHandle.WaitOne ();
				mre.Set ();
			}, null);
		}
 private long AsyncWriteToStream(Stream stream)
 {
     byte[] data = ConcatenateBufferAndAddIndividualOperations(stream);
     var resetEvent = new ManualResetEvent(false);
     pendingWritesHandles.Add(resetEvent);
     long positionAfterWrite = stream.Position + data.Length;
     stream.BeginWrite(data, 0, data.Length, delegate(IAsyncResult ar)
     {
         try
         {
             stream.EndWrite(ar);
         }
         catch (Exception e)
         {
             lock (pendingWritesFailures)
             {
                 pendingWritesFailures.Add(e);
             }
         }
         finally
         {
             resetEvent.Set();
         }
     }, null);
     return positionAfterWrite;
 }
Exemplo n.º 29
0
 /// <summary>
 /// 数据流异步写
 /// </summary>
 /// <param name="stream">数据流</param>
 /// <param name="buffer">目标字节数组</param>
 /// <param name="offset">目标起始位置</param>
 /// <param name="count">读取数据字节数</param>
 /// <param name="state">绑定用户对象</param>
 public streamWriter(Stream stream, byte[] buffer, int offset, int count, object state)
 {
     this.stream = stream;
     try
     {
         stream.BeginWrite(buffer, offset, count, onWrite, state);
     }
     catch (Exception error)
     {
         this.error = error;
         completed();
     }
 }
Exemplo n.º 30
0
        private Result Write(Action<string> activity, Stream stream, byte[] buffer, int offset, int count, Result result)
        {
            // asynchronously execute read operation
            Result<IAsyncResult> inner = new Result<IAsyncResult>(TimeSpan.MaxValue);
            inner.WhenDone(delegate(Result<IAsyncResult> _unused) {
                try {
                    activity(string.Format("pre {0}!EndWrite", stream.GetType().FullName));
                    stream.EndWrite(inner.Value);
                    activity("post EndWrite");
                    result.Return();
                } catch(Exception e) {
                    activity("throw Write 1");
                    result.Throw(e);
                }
            });
            try {
                activity(string.Format("pre {0}!BeginWrite", stream.GetType().FullName));
                stream.BeginWrite(buffer, offset, count, inner.Return, stream);
                activity("post BeginWrite");
            } catch(Exception e) {
                activity("throw Write 2");
                result.Throw(e);
            }

            // return yield handle
            return result;
        }
Exemplo n.º 31
0
        public static void StreamWriteAsync(
            Stream stream, 
            byte[] buffer, 
            int offset, 
            int count, 
            SynchronizationContextWrapper syncContext, 
            Action<int, Exception> callback)
        {
            Debug.Assert(syncContext != null);

            stream.BeginWrite(
                buffer,
                offset,
                count,
                delegate(IAsyncResult ar)
                {
                    if (ar.IsCompleted)
                    {
                        Exception error = null;
                        try
                        {
                            stream.EndWrite(ar);
                            stream.Flush();
                        }
                        catch (IOException ioe)
                        {
                            error = ioe;
                        }
                        finally
                        {
                            syncContext.Post(() => callback(count, error));
                        }
                    }
                },
                null);
        }
Exemplo n.º 32
0
        public static Action WriteToStream(this BodyAction body, Stream stream, Action<Exception> error, Action complete)
        {
            Action[] cancel = {() => { }};
            int[] completion = {0};
            Action<Exception> errorHandler = ex => { if (Interlocked.Increment(ref completion[0]) == 1) error(ex); };
            cancel[0] = body(
                (data, continuation) =>
                {
                    if (completion[0] != 0)
                        return false;
                    try
                    {
                        if (continuation == null)
                        {
                            stream.Write(data.Array, data.Offset, data.Count);
                            return false;
                        }
                        var sr = stream.BeginWrite(data.Array, data.Offset, data.Count, ar =>
                        {
                            if (ar.CompletedSynchronously) return;
                            try
                            {
                                stream.EndWrite(ar);
                            }
                            catch (Exception ex)
                            {
                                error(ex);
                            }
                            continuation();
                        }, null);
                        if (sr.CompletedSynchronously)
                        {
                            stream.EndWrite(sr);
                            return false;
                        }

                        return true;
                    }
                    catch (Exception ex)
                    {
                        errorHandler(ex);
                        cancel[0]();
                        return false;
                    }
                },
                errorHandler,
                () => { if (Interlocked.Increment(ref completion[0]) == 1) complete(); });

            return () =>
            {
                Interlocked.Increment(ref completion[0]);
                cancel[0]();
            };
        }
Exemplo n.º 33
0
            public override void write(byte[] buffer, int offset, int size,
					 ResultHandler rh)
            {
                if (mResponse != null)
                    throw new Exception("HTTP write");
                if (mStream == null)
                {
                    mRequest.BeginGetRequestStream(
                            new AsyncCallback(delegate(IAsyncResult ar)
                    {
                        mStream = mRequest.EndGetRequestStream(ar);
                        mStream.BeginWrite(buffer, offset, size,
                                new AsyncCallback(WriteCallback), rh);
                    }), rh);
                    return;
                }
                mStream.BeginWrite(buffer, offset, size,
                        new AsyncCallback(WriteCallback), rh);
            }
Exemplo n.º 34
0
        /// <summary>
        /// Starts writing response to the specified stream.
        /// </summary>
        /// <param name="session">Owner IMAP session.</param>
        /// <param name="stream">Stream where to store response.</param>
        /// <param name="mailboxEncoding">Specifies how mailbox name is encoded.</param>
        /// <param name="completedAsyncCallback">Callback to be called when this method completes asynchronously.</param>
        /// <returns>Returns true is method completed asynchronously(the completedAsyncCallback is raised upon completion of the operation).
        /// Returns false if operation completed synchronously.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception>
        protected override bool ToStreamAsync(IMAP_Session session,Stream stream,IMAP_Mailbox_Encoding mailboxEncoding,EventHandler<EventArgs<Exception>> completedAsyncCallback)
        {
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            StringBuilder buffer = new StringBuilder();
            buffer.Append("* " + m_MsgSeqNo + " FETCH (");

            for(int i=0;i<m_pDataItems.Count;i++){
                IMAP_t_Fetch_r_i dataItem = m_pDataItems[i];

                if(i > 0){
                    buffer.Append(" ");
                }

                if(dataItem is IMAP_t_Fetch_r_i_Flags){
                    buffer.Append("FLAGS (" + ((IMAP_t_Fetch_r_i_Flags)dataItem).Flags.ToString() + ")");
                }
                else if(dataItem is IMAP_t_Fetch_r_i_Uid){
                    buffer.Append("UID " + ((IMAP_t_Fetch_r_i_Uid)dataItem).UID.ToString());
                }
                else{
                    throw new NotImplementedException("Fetch response data-item '" + dataItem.ToString() + "' not implemented.");
                }
            }

            buffer.Append(")\r\n");

            string responseS = buffer.ToString();
            byte[] response  = Encoding.UTF8.GetBytes(responseS);

            // Log.
            if(session != null){
                session.LogAddWrite(response.Length,responseS.TrimEnd());
            }

            // Starts writing response to stream.
            IAsyncResult ar = stream.BeginWrite(
                response,
                0,
                response.Length,
                delegate(IAsyncResult r){
                    if(r.CompletedSynchronously){
                        return;
                    }

                    try{
                        stream.EndWrite(r);

                        if(completedAsyncCallback != null){
                            completedAsyncCallback(this,new EventArgs<Exception>(null));
                        }
                    }
                    catch(Exception x){
                        if(completedAsyncCallback != null){
                            completedAsyncCallback(this,new EventArgs<Exception>(x));
                        }
                    }
                },
                null
            );
            // Completed synchronously, process result.
            if(ar.CompletedSynchronously){
                stream.EndWrite(ar);

                return false;
            }
            // Completed asynchronously, stream.BeginWrite AsyncCallback will continue processing.
            else{
                return true;
            }
        }
Exemplo n.º 35
0
			public static bool BeginIO(Stream stream, PhpStream phpStream, StreamAccessOptions access, int desc_no)
			{
				if (access == StreamAccessOptions.Read && !phpStream.CanWrite ||
				  access == StreamAccessOptions.Write && !phpStream.CanRead)
				{
					PhpException.Throw(PhpError.Warning, LibResources.GetString("descriptor_item_invalid_mode", desc_no));
					return false;
				}

				ActivePipe pipe = new ActivePipe();
				pipe.stream = stream;
				pipe.phpStream = phpStream;
				pipe.access = access;
				pipe.callback = new AsyncCallback(pipe.Callback);

				if (access == StreamAccessOptions.Read)
				{
                    var buffer = new byte[BufferSize];
                    stream.BeginRead(buffer, 0, buffer.Length, pipe.callback, null);
                    pipe.buffer = new PhpBytes(buffer);
				}
				else
				{
					pipe.buffer = phpStream.ReadBytes(BufferSize);
					if (pipe.buffer != null)
						stream.BeginWrite(pipe.buffer.ReadonlyData, 0, pipe.buffer.Length, pipe.callback, null);
					else
						stream.Close();
				}

				return true;
			}
Exemplo n.º 36
0
        private void CopyStreamAsync(Stream input, Stream output, bool flushInput, bool flushOutput, StreamCopyCompletedDelegate completed)
        {
            byte[] buffer = new byte[1024 * 4];
            var asyncOp = System.ComponentModel.AsyncOperationManager.CreateOperation(null);

            Action<Exception> done = e =>
            {
                if (completed != null) asyncOp.Post(delegate
                    {
                        completed(input, output, e);
                    }, null);
            };

            AsyncCallback rc = null;
            rc = readResult =>
            {
                try
                {
                    int read = input.EndRead(readResult);
                    if (read > 0)
                    {
                        if (flushInput) input.Flush();
                        output.BeginWrite(buffer, 0, read, writeResult =>
                        {
                            try
                            {
                                output.EndWrite(writeResult);
                                if (flushOutput) output.Flush();
                                input.BeginRead(buffer, 0, buffer.Length, rc, null);
                            }
                            catch (Exception exc) { done(exc); }
                        }, null);
                    }
                    else done(null);
                }
                catch (Exception exc) { done(exc); }
            };

            input.BeginRead(buffer, 0, buffer.Length, rc, null);
        }
Exemplo n.º 37
0
 /// <summary>
 /// Begins an asynchronous write operation.
 /// </summary>
 /// <param name="stream">The stream to write to.</param>
 /// <param name="buffer">The buffer to write data from.</param>
 /// <param name="callback">The callback to which a System.IO.AsyncStreamOperationState object is passed.</param>
 public static void BeginWrite(this Stream stream, byte[] buffer, AsyncCallback callback)
 {
     stream.BeginWrite(buffer, 0, buffer.Length, callback, new StreamAsyncState(stream, buffer));
 }
Exemplo n.º 38
-1
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            Contract.Assert(stream != null);

            // Serialize header
            byte[] header = SerializeHeader();

            TaskCompletionSource<object> writeTask = new TaskCompletionSource<object>();
            try
            {
                // We don't use TaskFactory.FromAsync as it generates an FxCop CA908 error
                Tuple<HttpMessageContent, Stream, TaskCompletionSource<object>> state =
                    new Tuple<HttpMessageContent, Stream, TaskCompletionSource<object>>(this, stream, writeTask);
                IAsyncResult result = stream.BeginWrite(header, 0, header.Length, _onWriteComplete, state);
                if (result.CompletedSynchronously)
                {
                    WriteComplete(result, this, stream, writeTask);
                }
            }
            catch (Exception e)
            {
                writeTask.TrySetException(e);
            }

            return writeTask.Task;
        }