EndWrite() 공개 메소드

public EndWrite ( IAsyncResult asyncResult ) : void
asyncResult IAsyncResult
리턴 void
        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();
 }
예제 #3
0
        public override void EndWrite(IAsyncResult ares)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(GetType().ToString());
            }

            if (ignore_errors)
            {
                try {
                    stream.EndWrite(ares);
                    if (response.SendChunked)
                    {
                        stream.Write(crlf, 0, 2);
                    }
                } catch { }
            }
            else
            {
                stream.EndWrite(ares);
                if (response.SendChunked)
                {
                    stream.Write(crlf, 0, 2);
                }
            }
        }
        // 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;
        }
예제 #5
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;
        }
예제 #6
0
            protected void WriteCallback(IAsyncResult ar)
            {
                ResultHandler rh = (ResultHandler)ar.AsyncState;

                mStream.EndWrite(ar);
                rh(mHandle, MoSync.Constants.CONNOP_WRITE, 1);
            }
예제 #7
0
파일: EndWrite.cs 프로젝트: maikahj/corefx
    public bool VerifyEndWriteException(System.IO.Stream serialStream, IAsyncResult asyncResult, Type expectedException)
    {
        bool retValue = true;

        try
        {
            serialStream.EndWrite(asyncResult);

            if (null != expectedException)
            {
                Console.WriteLine("ERROR!!!: No Excpetion was thrown");
                retValue = false;
            }
        }
        catch (System.Exception e)
        {
            if (null == expectedException)
            {
                Console.WriteLine("ERROR!!!: Expected no exception to be thrown and {0} was thrown", e);
                retValue = false;
            }
            else if (e.GetType() != expectedException)
            {
                Console.WriteLine("ERROR!!!:  Expected {0} to be thrown and the following exception was thrown:\n{1}", expectedException, e);
                retValue = false;
            }
        }
        return(retValue);
    }
예제 #8
0
 public override void EndWrite(
     IAsyncResult asyncResult
     )
 {
     Trace.WriteLine("TraceStream", "EndWrite()");
     m_in.EndWrite(asyncResult);
 }
예제 #9
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;
        }
예제 #11
0
 private static void EndWrite(Stream stream, IAsyncResult ar, byte[] buffer)
 {
     try
     {
         stream.EndWrite(ar);
     }
     catch (Exception)
     {
         stream.WriteAsync(buffer).Wait();
     }
 }
예제 #12
0
 private static void FinishWriteAsync(Stream stream, IAsyncResult asyncResult, TaskCompletionSource<int> taskCompletionSource) {
     try {
         stream.EndWrite(asyncResult);
         taskCompletionSource.SetResult(0);
     }
     catch (OperationCanceledException) {
         taskCompletionSource.TrySetCanceled();
     }
     catch (Exception exception) {
         taskCompletionSource.SetException(exception);
     }
 }
예제 #13
0
        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();
        }
예제 #14
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);
        }
예제 #15
0
        private void OnWriteFinished(System.IAsyncResult ar)
        {
            object[]  objs    = (object[])ar.AsyncState;
            IO.Stream ostream = (IO.Stream)objs[0];
            PeerFinishedPieceTransfer callback = (PeerFinishedPieceTransfer)objs[1];
            object state = objs[2];

            try
            {
                ostream.EndWrite(ar);
                this.upthrottle.AddData((int)objs[3]);
                Config.LogDebugMessage("Piece sent: " + (int)objs[3]);

                callback(state, true);
            }
            catch (System.Exception)
            {
                callback(state, false);
            }
        }
예제 #16
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;
      }
예제 #17
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;
        }
예제 #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;
 }
예제 #19
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);
		}
예제 #20
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();
        }
예제 #21
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;
 }
예제 #22
0
        /// <include file='../_Doc/mscorlib.xml' path='doc/members/member[@name="M:System.IO.Stream.EndWrite(System.IAsyncResult)"]/*' />
        /// <param name="stream">Stream on which to end writing.</param>
        public static void EndWrite(this Stream stream, IAsyncResult asyncResult)
        {
#if DOTNET || WINDOWS_PHONE
            stream.EndWrite(asyncResult);
#endif
        }
예제 #23
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;
            }
        }
예제 #24
0
파일: Body.cs 프로젝트: bvanderveen/gate
        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]();
            };
        }
예제 #25
0
 public override void EndWrite(IAsyncResult asyncResult)
 {
     _innerStream.EndWrite(asyncResult);
 }
예제 #26
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;
        }
예제 #27
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);
        }
예제 #28
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;
            }
        }
        public static void CopyTo(this Stream input, Stream output, int buffer_size)
        {
            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[][] buffer = { new byte[buffer_size], new byte[buffer_size] };
            int[] length = { 0, 0 };
            int index = 0;
            IAsyncResult read = input.BeginRead(buffer[index], 0, buffer[index].Length, null, null);
            IAsyncResult write = null;

            while (true)
            {

                // wait for the read operation to complete
                read.AsyncWaitHandle.WaitOne();
                length[index] = input.EndRead(read);

                // if zero bytes read, the copy is complete
                if (length[index] == 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(buffer[index], 0, length[index], null, null);

                // toggle the current, in-use buffer
                // and start the read operation on the new buffer.
                //
                // Changed to use XOR to toggle between 0 and 1.
                // A little speedier than using a ternary expression.
                index ^= 1; // bufno = ( bufno == 0 ? 1 : 0 ) ;

                read = input.BeginRead(buffer[index], 0, buffer[index].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;
        }
예제 #30
0
 private void ProcessSelectedPart(int BufferSize, long Begin, long End, Stream fsRead, Stream fsWrite, CryptMethod3Key Algorythm, ulong[] KeyList1, ulong[] KeyList2, ulong[] KeyList3, ulong IV, bool FlipKey)
 {
     byte[] Buffer = new byte[BufferSize];
     byte[] CurBuffer = new byte[BufferSize];
     byte[] temp;
     IAsyncResult ReadResult;
     IAsyncResult WriteResult;
     fsRead.Seek(Begin, SeekOrigin.Begin);
     ReadResult = fsRead.BeginRead(Buffer, 0, BufferSize, null, null);
     fsRead.EndRead(ReadResult);
     long i;
     for (i = Begin + BufferSize; i < End; i += BufferSize)
     {
         fsRead.Seek(i, SeekOrigin.Begin);
         ReadResult = fsRead.BeginRead(CurBuffer, 0, BufferSize, null, null);
         Buffer = CryptBuffer(Buffer, Algorythm, KeyList1, KeyList2, KeyList3, ref IV, FlipKey);
         fsWrite.Seek(i - BufferSize, SeekOrigin.Begin);
         WriteResult = fsWrite.BeginWrite(Buffer, 0, BufferSize, null, null);
         fsRead.EndRead(ReadResult);
         fsWrite.EndWrite(WriteResult);
         temp = Buffer;
         Buffer = CurBuffer;
         CurBuffer = temp;
     }
     fsWrite.Seek(i - BufferSize, SeekOrigin.Begin);
     WriteResult = fsWrite.BeginWrite(Buffer, 0, BufferSize, null, null);
     fsWrite.EndWrite(WriteResult);
 }
예제 #31
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);
		}
예제 #32
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);
		}
예제 #33
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);
            }
        } 
 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;
 }
예제 #35
0
        private static void WriteComplete(IAsyncResult result, HttpMessageContent thisPtr, Stream stream, TaskCompletionSource<object> writeTask)
        {
            Contract.Assert(result != null, "result cannot be null");
            Contract.Assert(thisPtr != null, "thisPtr cannot be null");
            Contract.Assert(stream != null, "stream cannot be null");
            Contract.Assert(writeTask != null, "writeTask cannot be null");

            try
            {
                stream.EndWrite(result);
            }
            catch (Exception e)
            {
                writeTask.TrySetException(e);
            }

            thisPtr.PrepareContentAsync().Then(content =>
            {
                if (content != null)
                {
                    content.CopyToAsync(stream)
                        .CopyResultToCompletionSource(writeTask, completionResult: null);
                }
                else
                {
                    writeTask.TrySetResult(null);
                }
            });
        }
예제 #36
0
        public static void CopyStreamToStream(Stream source, Stream destination, int buffersize,
                                              Action<Stream, Stream, Exception> completed)
        {
            //byte[] buffer = new byte[0x2500];
            byte[] buffer = new byte[buffersize];
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(null);

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

            AsyncCallback[] rc = { null };
            rc[0] = readResult =>
                        {
                            try
                            {
                                int read = source.EndRead(readResult);
                                if (read > 0)
                                {
                                    destination.BeginWrite(buffer, 0, read, writeResult =>
                                                                                {
                                                                                    try
                                                                                    {
                                                                                        destination.EndWrite(writeResult);
                                                                                        source.BeginRead(
                                                                                            buffer, 0, buffer.Length,
                                                                                            rc[0], null);
                                                                                    }
                                                                                    catch (Exception exc)
                                                                                    {
                                                                                        done(exc);
                                                                                    }
                                                                                }, null);
                                }
                                else done(null);
                            }
                            catch (Exception exc) { done(exc); }
                        };

            source.BeginRead(buffer, 0, buffer.Length, rc[0], null);
        }
예제 #37
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);
        }
예제 #38
0
 public override void EndWrite(IAsyncResult asyncResult)
 {
     lock (_stream)
         _stream.EndWrite(asyncResult);
 }