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

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

            try
            {
                PrepareMessage();

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

                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);
                var logEventMsgSet    = new LogEventMsgSet(asyncLogEventInfo, buffer, messageBuilder, messageTransmitter);

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

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