void DequeueAndFlush(ByteBuffer currentBuffer, AsyncEventArgsCallback callback)
        {
            // Dequeue does a checkout of the buffer from its slot.
            // the callback for the [....] path only enqueues the buffer.
            // The WriteAsync callback needs to enqueue and also complete.
            this.currentByteBuffer = null;
            ByteBuffer dequeued = this.buffers.Dequeue();

            Fx.Assert(dequeued == currentBuffer, "Buffer queue in an inconsistent state.");

            WriteFlushAsyncEventArgs writeflushState = (WriteFlushAsyncEventArgs)currentBuffer.FlushAsyncArgs;

            if (writeflushState == null)
            {
                writeflushState = new WriteFlushAsyncEventArgs();
                currentBuffer.FlushAsyncArgs = writeflushState;
            }

            writeflushState.Set(callback, null, this);
            if (currentBuffer.FlushAsync() == AsyncCompletionResult.Completed)
            {
                this.buffers.Enqueue(currentBuffer);
                writeflushState.Complete(true);
            }
        }
        static void OnFlushComplete(IAsyncEventArgs state)
        {
            BufferedOutputAsyncStream thisPtr    = (BufferedOutputAsyncStream)state.AsyncState;
            WriteFlushAsyncEventArgs  flushState = (WriteFlushAsyncEventArgs)state;
            ByteBuffer byteBuffer = flushState.Result;

            thisPtr.buffers.Enqueue(byteBuffer);
        }
        static void OnAsyncFlushComplete(IAsyncEventArgs state)
        {
            BufferedOutputAsyncStream thisPtr = (BufferedOutputAsyncStream)state.AsyncState;
            Exception completionException     = null;
            bool      completeSelf            = false;

            try
            {
                OnFlushComplete(state);

                if (thisPtr.buffers.TryAcquireLock())
                {
                    WriteFlushAsyncEventArgs flushState = (WriteFlushAsyncEventArgs)state;
                    if (flushState.Exception != null)
                    {
                        completeSelf        = true;
                        completionException = flushState.Exception;
                    }
                    else
                    {
                        if (thisPtr.WriteAsync(thisPtr.writeState) == AsyncCompletionResult.Completed)
                        {
                            completeSelf = true;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (Fx.IsFatal(exception))
                {
                    throw;
                }

                if (completionException == null)
                {
                    completionException = exception;
                }

                completeSelf = true;
            }

            if (completeSelf)
            {
                thisPtr.writeState.Complete(false, completionException);
            }
        }