private Task SendAsync(CancellationToken token, TaskCompletionSource <object> tcs)
        {
            if (token.IsCancellationRequested)
            {
                return(tcs.CanceledTask());
            }

            var allSent = currentMessage == logEntries.Length;

            if (allSent)
            {
                return(tcs.SucceededTask(() => asyncLogEvent.Continuation(null)));
            }

            try
            {
                PrepareMessage();

                messageTransmitter
                .SendMessageAsync(buffer, token)
                .ContinueWith(t =>
                {
                    if (t.IsCanceled)
                    {
                        tcs.SetCanceled();
                        return;
                    }
                    if (t.Exception != null)
                    {
                        asyncLogEvent.Continuation(t.Exception.GetBaseException());
                        tcs.SetException(t.Exception);
                        return;
                    }
                    SendAsync(token, tcs);
                }, token, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Current);

                return(tcs.Task);
            }
            catch (Exception exception)
            {
                return(tcs.FailedTask(exception));
            }
        }
        private Task ProcessQueueAsync(MessageBuilder messageBuilder, TaskCompletionSource <object> tcs)
        {
            if (token.IsCancellationRequested)
            {
                return(tcs.CanceledTask());
            }

            try
            {
                var asyncLogEventInfo = queue.Take(token);
                SignalFlushCompletionWhenIsMarker(asyncLogEventInfo);
                var logEventMsgSet = new LogEventMsgSet(asyncLogEventInfo, buffer, messageBuilder, messageTransmitter);

                logEventMsgSet
                .Build(layout)
                .SendAsync(token)
                .ContinueWith(t =>
                {
                    if (t.IsCanceled)
                    {
                        InternalLogger.Debug("Task canceled");
                        tcs.SetCanceled();
                        return;
                    }
                    if (t.Exception != null)     // t.IsFaulted is true
                    {
                        InternalLogger.Warn(t.Exception.GetBaseException(), "Task faulted");
                    }
                    else
                    {
                        InternalLogger.Debug("Successfully sent message '{0}'", logEventMsgSet);
                    }
                    ProcessQueueAsync(messageBuilder, tcs);
                }, token, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Current);

                return(tcs.Task);
            }
            catch (Exception exception)
            {
                return(tcs.FailedTask(exception));
            }
        }