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