public void OnNextWrite(AsyncWriteHandler handler)
        {
            var myAction = new MyAction(handler);

            if (Interlocked.CompareExchange(ref writeAction, myAction, null) != null)
            {
                throw new InvalidOperationException();
            }
        }
        async Task WriteAsync(byte[] buffer, int offset, int count, string message,
                              AsyncWriteFunc func, AsyncWriteHandler handler, CancellationToken cancellationToken)
        {
            Context.LogDebug(4, message);
            try {
                await handler(buffer, offset, count, func, cancellationToken).ConfigureAwait(false);

                Context.LogDebug(4, "{0} done", message);
            } catch (Exception ex) {
                Context.LogDebug(4, "{0} failed: {1}", message, ex);
                throw;
            }
        }
        public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            var message = string.Format("{0}.WriteAsync({1},{2})", Name, offset, count);

            AsyncWriteFunc    asyncBaseWrite    = base.WriteAsync;
            AsyncWriteHandler asyncWriteHandler = (b, o, c, func, ct) => func(b, o, c, ct);

            var action = Interlocked.Exchange(ref writeAction, null);

            if (action?.AsyncWrite != null)
            {
                message += " - action";
                return(WriteAsync(buffer, offset, count, message, asyncBaseWrite, action.AsyncWrite, cancellationToken));
            }

            return(WriteAsync(buffer, offset, count, message, asyncBaseWrite, asyncWriteHandler, cancellationToken));
        }
        async Task WriteAsync(byte[] buffer, int offset, int count, string message,
                              AsyncWriteFunc func, AsyncWriteHandler handler, CancellationToken cancellationToken)
        {
            LogDebug(message);
            try {
                await handler(buffer, offset, count, func, cancellationToken).ConfigureAwait(false);

                LogDebug($"{message} done");
            } catch (Exception ex) {
                if (IgnoreErrors)
                {
                    return;
                }
                LogDebug($"{message} failed: {ex}");
                throw;
            }
        }
 public MyAction(AsyncWriteHandler handler)
 {
     AsyncWrite = handler;
 }