File: BufferedOutputAsyncStream.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (1013 lines) | stat: -rw-r--r-- 34,213 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.IO;
    using System.Runtime;
    using System.Runtime.Diagnostics;
    using System.ServiceModel;
    using System.ServiceModel.Diagnostics.Application;
    using System.Threading;


    /// <summary>
    /// 
    /// BufferedOutputAsyncStream is used for writing streamed response.
    /// For performance reasons, the behavior we want is chunk, chunk, chunk,.. terminating chunk  without a delay.
    /// We call BeginWrite,BeginWrite,BeginWrite and Close()(close sends the terminating chunk) without 
    /// waiting for all outstanding BeginWrites to complete.
    /// 
    /// BufferedOutputAsyncStream is not a general-purpose stream wrapper, it requires that the base stream
    ///     1. allow concurrent IO (for multiple BeginWrite calls)
    ///     2. support the BeginWrite,BeginWrite,BeginWrite,.. Close() calling pattern.
    /// 
    /// Currently BufferedOutputAsyncStream only used to wrap the System.Net.HttpResponseStream, which satisfy both requirements.
    /// 
    /// BufferedOutputAsyncStream can also be used when doing asynchronous operations. [....] operations are not allowed when an async
    /// operation is in-flight. If a [....] operation is in progress (i.e., data exists in our CurrentBuffer) and we issue an async operation, 
    /// we flush everything in the buffers (and block while doing so) before the async operation is allowed to proceed. 
    ///     
    /// </summary>
    class BufferedOutputAsyncStream : Stream
    {
        readonly Stream stream;
        readonly int bufferSize;
        readonly int bufferLimit;
        readonly BufferQueue buffers;
        ByteBuffer currentByteBuffer;
        int availableBufferCount;
        static AsyncEventArgsCallback onFlushComplete = new AsyncEventArgsCallback(OnFlushComplete);
        int asyncWriteCount;
        WriteAsyncState writeState;
        WriteAsyncArgs writeArgs;
        static AsyncEventArgsCallback onAsyncFlushComplete;
        static AsyncEventArgsCallback onWriteCallback;
        EventTraceActivity activity;
        bool closed;

        internal BufferedOutputAsyncStream(Stream stream, int bufferSize, int bufferLimit)
        {
            this.stream = stream;
            this.bufferSize = bufferSize;
            this.bufferLimit = bufferLimit;
            this.buffers = new BufferQueue(this.bufferLimit);
            this.buffers.Add(new ByteBuffer(this, this.bufferSize, stream));
            this.availableBufferCount = 1;
        }

        public override bool CanRead
        {
            get { return false; }
        }

        public override bool CanSeek
        {
            get { return false; }
        }

        public override bool CanWrite
        {
            get { return stream.CanWrite && (!this.closed); }
        }

        public override long Length
        {
            get
            {
#pragma warning suppress 56503 // [....], required by the Stream.Length contract
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ReadNotSupported)));
            }
        }

        public override long Position
        {
            get
            {
#pragma warning suppress 56503 // [....], required by the Stream.Position contract
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
            }
            set
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
            }
        }

        internal EventTraceActivity EventTraceActivity
        {
            get
            {
                if (TD.BufferedAsyncWriteStartIsEnabled())
                {
                    if (this.activity == null)
                    {
                        this.activity = EventTraceActivity.GetFromThreadOrCreate();
                    }
                }

                return this.activity;
            }
        }

        ByteBuffer GetCurrentBuffer()
        {
            // Dequeue will null out the buffer
            this.ThrowOnException();
            if (this.currentByteBuffer == null)
            {
                this.currentByteBuffer = this.buffers.CurrentBuffer();
            }

            return this.currentByteBuffer;
        }

        public override void Close()
        {
            try
            {
                if (!this.closed)
                {
                    this.FlushPendingBuffer();
                    stream.Close();
                    this.WaitForAllWritesToComplete();
                }
            }
            finally
            {
                this.closed = true;
            }
        }

        public override void Flush()
        {
            FlushPendingBuffer();
            stream.Flush();
        }

        void FlushPendingBuffer()
        {
            ByteBuffer asyncBuffer = this.buffers.CurrentBuffer();
            if (asyncBuffer != null)
            {
                this.DequeueAndFlush(asyncBuffer, onFlushComplete);
            }
        }

        void IncrementAsyncWriteCount()
        {
            if (Interlocked.Increment(ref this.asyncWriteCount) > 1)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(SR.WriterAsyncWritePending)));
            }
        }

        void DecrementAsyncWriteCount()
        {
            if (Interlocked.Decrement(ref this.asyncWriteCount) != 0)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(SR.NoAsyncWritePending)));
            }
        }

        void EnsureNoAsyncWritePending()
        {
            if (this.asyncWriteCount != 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.WriterAsyncWritePending)));
            }
        }

        void EnsureOpened()
        {
            if (this.closed)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.StreamClosed)));
            }
        }

        ByteBuffer NextBuffer()
        {
            if (!this.AdjustBufferSize())
            {
                this.buffers.WaitForAny();
            }

            return this.GetCurrentBuffer();
        }

        bool AdjustBufferSize()
        {
            if (this.availableBufferCount < this.bufferLimit)
            {
                buffers.Add(new ByteBuffer(this, bufferSize, stream));
                this.availableBufferCount++;
                return true;
            }

            return false;
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ReadNotSupported)));
        }

        public override int ReadByte()
        {
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ReadNotSupported)));
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
        }

        public override void SetLength(long value)
        {
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
        }

        void WaitForAllWritesToComplete()
        {
            // Complete all outstanding writes 
            this.buffers.WaitForAllWritesToComplete();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            this.EnsureOpened();
            this.EnsureNoAsyncWritePending();

            while (count > 0)
            {
                ByteBuffer currentBuffer = this.GetCurrentBuffer();
                if (currentBuffer == null)
                {
                    currentBuffer = this.NextBuffer();
                }

                int freeBytes = currentBuffer.FreeBytes;   // space left in the CurrentBuffer
                if (freeBytes > 0)
                {
                    if (freeBytes > count)
                        freeBytes = count;

                    currentBuffer.CopyData(buffer, offset, freeBytes);
                    offset += freeBytes;
                    count -= freeBytes;
                }
                if (currentBuffer.FreeBytes == 0)
                {
                    this.DequeueAndFlush(currentBuffer, onFlushComplete);
                }
            }
        }

        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
        {
            this.EnsureOpened();
            this.IncrementAsyncWriteCount();

            Fx.Assert(this.writeState == null ||
                this.writeState.Arguments == null ||
                this.writeState.Arguments.Count <= 0,
                "All data has not been written yet.");

            if (onWriteCallback == null)
            {
                onWriteCallback = new AsyncEventArgsCallback(OnWriteCallback);
                onAsyncFlushComplete = new AsyncEventArgsCallback(OnAsyncFlushComplete);
            }

            if (this.writeState == null)
            {
                this.writeState = new WriteAsyncState();
                this.writeArgs = new WriteAsyncArgs();
            }
            else
            {
                // Since writeState!= null, check if the stream has an  
                // exception as the async path has already been invoked.
                this.ThrowOnException();
            }

            this.writeArgs.Set(buffer, offset, count, callback, state);
            this.writeState.Set(onWriteCallback, this.writeArgs, this);
            if (this.WriteAsync(this.writeState) == AsyncCompletionResult.Completed)
            {
                this.writeState.Complete(true);
                if (callback != null)
                {
                    callback(this.writeState.CompletedSynchronouslyAsyncResult);
                }

                return this.writeState.CompletedSynchronouslyAsyncResult;
            }

            return this.writeState.PendingAsyncResult;
        }

        public override void EndWrite(IAsyncResult asyncResult)
        {
            this.DecrementAsyncWriteCount();
            this.ThrowOnException();
        }

        public override void WriteByte(byte value)
        {
            this.EnsureNoAsyncWritePending();
            ByteBuffer currentBuffer = this.GetCurrentBuffer();
            if (currentBuffer == null)
            {
                currentBuffer = NextBuffer();
            }

            currentBuffer.CopyData(value);
            if (currentBuffer.FreeBytes == 0)
            {
                this.DequeueAndFlush(currentBuffer, onFlushComplete);
            }
        }

        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);
        }

        AsyncCompletionResult WriteAsync(WriteAsyncState state)
        {
            Fx.Assert(state != null && state.Arguments != null, "Invalid WriteAsyncState parameter.");

            if (state.Arguments.Count == 0)
            {
                return AsyncCompletionResult.Completed;
            }

            byte[] buffer = state.Arguments.Buffer;
            int offset = state.Arguments.Offset;
            int count = state.Arguments.Count;

            ByteBuffer currentBuffer = this.GetCurrentBuffer();
            while (count > 0)
            {
                if (currentBuffer == null)
                {
                    throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(SR.WriteAsyncWithoutFreeBuffer)));
                }

                int freeBytes = currentBuffer.FreeBytes;   // space left in the CurrentBuffer
                if (freeBytes > 0)
                {
                    if (freeBytes > count)
                        freeBytes = count;

                    currentBuffer.CopyData(buffer, offset, freeBytes);
                    offset += freeBytes;
                    count -= freeBytes;
                }

                if (currentBuffer.FreeBytes == 0)
                {
                    this.DequeueAndFlush(currentBuffer, onAsyncFlushComplete);

                    // We might need to increase the number of buffers available
                    // if there is more data to be written or no buffer is available.
                    if (count > 0 || this.buffers.Count == 0)
                    {
                        this.AdjustBufferSize();
                    }
                }

                //Update state for any pending writes.
                state.Arguments.Offset = offset;
                state.Arguments.Count = count;

                // We can complete synchronously only 
                // if there a buffer available for writes.
                currentBuffer = this.GetCurrentBuffer();
                if (currentBuffer == null)
                {
                    if (this.buffers.TryUnlock())
                    {
                        return AsyncCompletionResult.Queued;
                    }

                    currentBuffer = this.GetCurrentBuffer();
                }
            }

            return AsyncCompletionResult.Completed;
        }

        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);
            }
        }

        static void OnWriteCallback(IAsyncEventArgs state)
        {
            BufferedOutputAsyncStream thisPtr = (BufferedOutputAsyncStream)state.AsyncState;
            IAsyncResult returnResult = thisPtr.writeState.PendingAsyncResult;
            AsyncCallback callback = thisPtr.writeState.Arguments.Callback;
            thisPtr.writeState.Arguments.Callback = null;
            if (callback != null)
            {
                callback(returnResult);
            }
        }

        void ThrowOnException()
        {
            // if any of the buffers or the write state has an
            // exception the stream is not usable anymore.
            this.buffers.ThrowOnException();
            if (this.writeState != null)
            {
                this.writeState.ThrowOnException();
            }
        }

        class BufferQueue
        {
            readonly List<ByteBuffer> refBufferList;
            readonly int size;
            readonly Slot[] buffers;
            Exception completionException;
            int head;
            int count;
            bool waiting;
            bool pendingCompletion;

            internal BufferQueue(int queueSize)
            {
                this.head = 0;
                this.count = 0;
                this.size = queueSize;
                this.buffers = new Slot[size];
                this.refBufferList = new List<ByteBuffer>();
                for (int i = 0; i < queueSize; i++)
                {
                    Slot s = new Slot();
                    s.checkedOut = true; //Start with all buffers checkedout.
                    this.buffers[i] = s;
                }
            }

            object ThisLock
            {
                get
                {
                    return this.buffers;
                }
            }

            internal int Count
            {
                get
                {
                    lock (ThisLock)
                    {
                        return count;
                    }
                }
            }

            internal ByteBuffer Dequeue()
            {
                Fx.Assert(!this.pendingCompletion, "Dequeue cannot be invoked when there is a pending completion");

                lock (ThisLock)
                {
                    if (count == 0)
                    {
                        return null;
                    }

                    Slot s = buffers[head];
                    Fx.Assert(!s.checkedOut, "This buffer is already in use.");

                    this.head = (this.head + 1) % size;
                    this.count--;
                    ByteBuffer buffer = s.buffer;
                    s.buffer = null;
                    s.checkedOut = true;
                    return buffer;
                }
            }

            internal void Add(ByteBuffer buffer)
            {
                lock (ThisLock)
                {
                    Fx.Assert(this.refBufferList.Count < size, "Bufferlist is already full.");

                    if (this.refBufferList.Count < this.size)
                    {
                        this.refBufferList.Add(buffer);
                        this.Enqueue(buffer);
                    }
                }
            }

            internal void Enqueue(ByteBuffer buffer)
            {
                lock (ThisLock)
                {
                    this.completionException = this.completionException ?? buffer.CompletionException;
                    Fx.Assert(count < size, "The queue is already full.");
                    int tail = (this.head + this.count) % size;
                    Slot s = this.buffers[tail];
                    this.count++;
                    Fx.Assert(s.checkedOut, "Current buffer is still free.");
                    s.checkedOut = false;
                    s.buffer = buffer;

                    if (this.waiting)
                    {
                        Monitor.Pulse(this.ThisLock);
                    }
                }
            }

            internal ByteBuffer CurrentBuffer()
            {
                lock (ThisLock)
                {
                    ThrowOnException();
                    Slot s = this.buffers[head];
                    return s.buffer;
                }
            }

            internal void WaitForAllWritesToComplete()
            {
                for (int i = 0; i < this.refBufferList.Count; i++)
                {
                    this.refBufferList[i].WaitForWriteComplete();
                }
            }

            internal void WaitForAny()
            {
                lock (ThisLock)
                {
                    if (this.count == 0)
                    {
                        this.waiting = true;
                        Monitor.Wait(ThisLock);
                        this.waiting = false;
                    }
                }

                this.ThrowOnException();
            }

            internal void ThrowOnException()
            {
                if (this.completionException != null)
                {
                    throw FxTrace.Exception.AsError(this.completionException);
                }
            }

            internal bool TryUnlock()
            {
                // The main thread tries to indicate a pending completion 
                // if there aren't any free buffers for the next write.
                // The callback should try to complete() through TryAcquireLock.
                lock (ThisLock)
                {
                    Fx.Assert(!this.pendingCompletion, "There is already a completion pending.");

                    if (this.count == 0)
                    {
                        this.pendingCompletion = true;
                        return true;
                    }
                }

                return false;
            }

            internal bool TryAcquireLock()
            {
                // The callback tries to acquire the lock if there is a pending completion and a free buffer.
                // Buffers might get dequeued by the main writing thread as soon as they are enqueued.
                lock (ThisLock)
                {
                    if (this.pendingCompletion && this.count > 0)
                    {
                        this.pendingCompletion = false;
                        return true;
                    }
                }

                return false;
            }

            class Slot
            {
                internal bool checkedOut;
                internal ByteBuffer buffer;
            }
        }

        /// <summary>
        /// AsyncEventArgs used to invoke the FlushAsync() on the ByteBuffer.
        /// </summary>
        class WriteFlushAsyncEventArgs : AsyncEventArgs<object, ByteBuffer>
        {
        }

        class ByteBuffer
        {
            byte[] bytes;
            int position;
            Stream stream;
            bool writePending;
            bool waiting;
            Exception completionException;
            BufferedOutputAsyncStream parent;

            static AsyncCallback writeCallback = Fx.ThunkCallback(new AsyncCallback(WriteCallback));
            static AsyncCallback flushCallback;

            internal ByteBuffer(BufferedOutputAsyncStream parent, int bufferSize, Stream stream)
            {
                this.waiting = false;
                this.writePending = false;
                this.position = 0;
                this.bytes = DiagnosticUtility.Utility.AllocateByteArray(bufferSize);
                this.stream = stream;
                this.parent = parent;
            }

            object ThisLock
            {
                get { return this; }
            }

            internal Exception CompletionException
            {
                get { return this.completionException; }
            }

            internal int FreeBytes
            {
                get
                {
                    return this.bytes.Length - this.position;
                }
            }

            internal AsyncEventArgs<object, ByteBuffer> FlushAsyncArgs
            {
                get;
                set;
            }

            static void WriteCallback(IAsyncResult result)
            {
                if (result.CompletedSynchronously)
                    return;

                // Fetch our state information: ByteBuffer
                ByteBuffer buffer = (ByteBuffer)result.AsyncState;
                try
                {
                    if (TD.BufferedAsyncWriteStopIsEnabled())
                    {
                        TD.BufferedAsyncWriteStop(buffer.parent.EventTraceActivity);
                    }

                    buffer.stream.EndWrite(result);

                }
#pragma warning suppress 56500 // [....], transferring exception to another thread
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }
                    buffer.completionException = e;
                }

                // Tell the main thread we've finished.
                lock (buffer.ThisLock)
                {
                    buffer.writePending = false;

                    // Do not Pulse if no one is waiting, to avoid the overhead of Pulse
                    if (!buffer.waiting)
                        return;

                    Monitor.Pulse(buffer.ThisLock);
                }
            }

            internal void WaitForWriteComplete()
            {
                lock (ThisLock)
                {
                    if (this.writePending)
                    {
                        // Wait until the async write of this buffer is finished.
                        this.waiting = true;
                        Monitor.Wait(ThisLock);
                        this.waiting = false;
                    }
                }

                // Raise exception if necessary
                if (this.completionException != null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(completionException);
                }
            }

            internal void CopyData(byte[] buffer, int offset, int count)
            {
                Fx.Assert(this.position + count <= this.bytes.Length, string.Format(CultureInfo.InvariantCulture, "Chunk is too big to fit in this buffer. Chunk size={0}, free space={1}", count, this.bytes.Length - this.position));
                Fx.Assert(!this.writePending, string.Format(CultureInfo.InvariantCulture, "The buffer is in use, position={0}", this.position));

                Buffer.BlockCopy(buffer, offset, this.bytes, this.position, count);
                this.position += count;
            }

            internal void CopyData(byte value)
            {
                Fx.Assert(this.position < this.bytes.Length, "Buffer is full");
                Fx.Assert(!this.writePending, string.Format(CultureInfo.InvariantCulture, "The buffer is in use, position={0}", this.position));

                this.bytes[this.position++] = value;
            }

            /// <summary>
            /// Set the ByteBuffer's FlushAsyncArgs to invoke FlushAsync()
            /// </summary>
            /// <returns></returns>
            internal AsyncCompletionResult FlushAsync()
            {
                if (this.position <= 0)
                    return AsyncCompletionResult.Completed;

                Fx.Assert(this.FlushAsyncArgs != null, "FlushAsyncArgs not set.");

                if (flushCallback == null)
                {
                    flushCallback = new AsyncCallback(OnAsyncFlush);
                }

                int bytesToWrite = this.position;
                this.SetWritePending();
                this.position = 0;

                if (TD.BufferedAsyncWriteStartIsEnabled())
                {
                    TD.BufferedAsyncWriteStart(this.parent.EventTraceActivity, this.GetHashCode(), bytesToWrite);
                }

                IAsyncResult asyncResult = this.stream.BeginWrite(this.bytes, 0, bytesToWrite, flushCallback, this);
                if (asyncResult.CompletedSynchronously)
                {
                    if (TD.BufferedAsyncWriteStopIsEnabled())
                    {
                        TD.BufferedAsyncWriteStop(this.parent.EventTraceActivity);
                    }

                    this.stream.EndWrite(asyncResult);
                    this.ResetWritePending();
                    return AsyncCompletionResult.Completed;
                }

                return AsyncCompletionResult.Queued;
            }

            static void OnAsyncFlush(IAsyncResult result)
            {
                if (result.CompletedSynchronously)
                {
                    return;
                }

                ByteBuffer thisPtr = (ByteBuffer)result.AsyncState;
                AsyncEventArgs<object, ByteBuffer> asyncEventArgs = thisPtr.FlushAsyncArgs;

                try
                {
                    ByteBuffer.WriteCallback(result);
                    asyncEventArgs.Result = thisPtr;
                }
                catch (Exception exception)
                {
                    if (Fx.IsFatal(exception))
                    {
                        throw;
                    }

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

                asyncEventArgs.Complete(false, thisPtr.completionException);
            }

            void ResetWritePending()
            {
                lock (ThisLock)
                {
                    this.writePending = false;
                }
            }

            void SetWritePending()
            {
                lock (ThisLock)
                {
                    if (this.writePending)
                    {
                        throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(SR.FlushBufferAlreadyInUse)));
                    }

                    this.writePending = true;
                }
            }
        }

        /// <summary>
        /// Used to hold the users callback and state and arguments when BeginWrite is invoked. 
        /// </summary>
        class WriteAsyncArgs
        {
            internal byte[] Buffer { get; set; }

            internal int Offset { get; set; }

            internal int Count { get; set; }

            internal AsyncCallback Callback { get; set; }

            internal object AsyncState { get; set; }

            internal void Set(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
            {
                this.Buffer = buffer;
                this.Offset = offset;
                this.Count = count;
                this.Callback = callback;
                this.AsyncState = state;
            }
        }

        class WriteAsyncState : AsyncEventArgs<WriteAsyncArgs, BufferedOutputAsyncStream>
        {
            PooledAsyncResult pooledAsyncResult;
            PooledAsyncResult completedSynchronouslyResult;

            internal IAsyncResult PendingAsyncResult
            {
                get
                {
                    if (this.pooledAsyncResult == null)
                    {
                        this.pooledAsyncResult = new PooledAsyncResult(this, false);
                    }

                    return this.pooledAsyncResult;
                }
            }

            internal IAsyncResult CompletedSynchronouslyAsyncResult
            {
                get
                {
                    if (this.completedSynchronouslyResult == null)
                    {
                        this.completedSynchronouslyResult = new PooledAsyncResult(this, true);
                    }

                    return completedSynchronouslyResult;
                }
            }

            internal void ThrowOnException()
            {
                if (this.Exception != null)
                {
                    throw FxTrace.Exception.AsError(this.Exception);
                }
            }

            class PooledAsyncResult : IAsyncResult
            {
                readonly WriteAsyncState writeState;
                readonly bool completedSynchronously;

                internal PooledAsyncResult(WriteAsyncState parentState, bool completedSynchronously)
                {
                    this.writeState = parentState;
                    this.completedSynchronously = completedSynchronously;
                }

                public object AsyncState
                {
                    get
                    {
                        return this.writeState.Arguments != null ? this.writeState.Arguments.AsyncState : null;
                    }
                }

                public WaitHandle AsyncWaitHandle
                {
                    get { throw FxTrace.Exception.AsError(new NotImplementedException()); }
                }

                public bool CompletedSynchronously
                {
                    get { return this.completedSynchronously; }
                }

                public bool IsCompleted
                {
                    get { throw FxTrace.Exception.AsError(new NotImplementedException()); }
                }
            }
        }
    }
}