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