Beispiel #1
0
        private Task SendAsync(CancellationToken token, TaskCompletionSource <object> tcs)
        {
            if (token.IsCancellationRequested)
            {
                tcs.SetCanceled();
                return(tcs.Task);
            }

            var allSent = currentMessage == logEntries.Length;

            if (allSent)
            {
                asyncLogEventInfo.Continuation(null);
                tcs.SetResult(null);
                return(tcs.Task);
            }

            try
            {
                PrepareMessage();

                messageTransmitter
                .SendMessageAsync(buffer, token)
                .ContinueWith(t =>
                {
                    var exception = t.Exception;
                    if (token.IsCancellationRequested || t.IsCanceled)
                    {
                        tcs.SetCanceled();
                        return;
                    }
                    if (exception != null)
                    {
                        asyncLogEventInfo.Continuation(exception.GetBaseException());
                        tcs.SetException(exception);
                        return;
                    }
                    SendAsync(token, tcs);
                }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Current);

                return(tcs.Task);
            }
            catch (Exception exception)
            {
                tcs.SetException(exception);
                return(tcs.Task);
            }
        }
        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));
            }
        }