Example #1
0
        private Task ProcessMessages(ITransportConnection connection, Func <Task> initialize)
        {
            var disposer = new Disposer();

            if (BeforeCancellationTokenCallbackRegistered != null)
            {
                BeforeCancellationTokenCallbackRegistered();
            }

            var cancelContext = new ForeverTransportContext(this, disposer);

            // Ensure delegate continues to use the C# Compiler static delegate caching optimization.
            IDisposable registration = ConnectionEndToken.SafeRegister(state => Cancel(state), cancelContext);

            var messageContext = new MessageContext(this, _transportLifetime, registration);

            if (BeforeReceive != null)
            {
                BeforeReceive();
            }

            try
            {
                // Ensure we enqueue the response initialization before any messages are received
                EnqueueOperation(state => InitializeResponse((ITransportConnection)state), connection)
                .Catch((ex, state) => OnError(ex, state), messageContext);

                // Ensure delegate continues to use the C# Compiler static delegate caching optimization.
                IDisposable subscription = connection.Receive(LastMessageId,
                                                              (response, state) => OnMessageReceived(response, state),
                                                              MaxMessages,
                                                              messageContext);


                disposer.Set(subscription);

                if (AfterReceive != null)
                {
                    AfterReceive();
                }

                // Ensure delegate continues to use the C# Compiler static delegate caching optimization.
                initialize().Then(tcs => tcs.TrySetResult(null), InitializeTcs)
                .Catch((ex, state) => OnError(ex, state), messageContext);
            }
            catch (OperationCanceledException ex)
            {
                InitializeTcs.TrySetCanceled();

                _transportLifetime.Complete(ex);
            }
            catch (Exception ex)
            {
                InitializeTcs.TrySetCanceled();

                _transportLifetime.Complete(ex);
            }

            return(_requestLifeTime.Task);
        }
Example #2
0
        protected void OnError(Exception ex)
        {
            IncrementErrors();

            // Cancel any pending writes in the queue
            InitializeTcs.TrySetCanceled();

            // Complete the http request
            _transportLifetime.Complete(ex);
        }