protected override void OnStartFailed()
        {
            // if the transport failed to start we want to stop it silently.
            _stop = true;

            _request.Abort();
        }
Пример #2
0
 /// <summary>
 /// Aborts the currently active polling request thereby forcing a reconnect.
 /// This will not trigger OnAbort.
 /// </summary>
 public void LostConnection()
 {
     lock (_stopLock)
     {
         if (_currentRequest != null)
         {
             _currentRequest.Abort();
         }
     }
 }
Пример #3
0
        /// <summary>
        /// Aborts the currently active polling request, does not stop the Polling Request Handler.
        /// </summary>
        private void Abort()
        {
            OnAbort(_currentRequest);

            if (_currentRequest != null)
            {
                // This will no-op if the request is already finished
                _currentRequest.Abort();
            }
        }
Пример #4
0
        protected override void OnStart(IConnection connection,
                                        string connectionData,
                                        CancellationToken disconnectToken,
                                        TransportInitializationHandler initializeHandler)
        {
            if (initializeHandler == null)
            {
                throw new ArgumentNullException("initializeHandler");
            }

            // Tie into the OnFailure event so that we can stop the transport silently.
            initializeHandler.OnFailure += () =>
            {
                _stop = true;

                _request.Abort();
            };

            OpenConnection(connection, connectionData, disconnectToken, initializeHandler.Success, initializeHandler.Fail);
        }
Пример #5
0
        public void Close()
        {
            if (_request != null)
            {
                // Always try to abort the request since close hangs if the connection is
                // being held open
                _request.Abort();
            }

            ((IDisposable)_response).Dispose();
        }
Пример #6
0
 public void AbortRequest()
 {
     CloseActiveStream();
     _request.Abort();
     if (statusCode == 0)
     {
         statusCode        = ERROR_CODE_ABORTED;
         statusDescription = "Request was aborted";
     }
     isActive = false;
 }
        /// <summary>
        /// Fully stops the polling loop.
        /// </summary>
        private void StopPolling()
        {
            lock (_stopLock)
            {
                if (Interlocked.Exchange(ref _running, 0) == 1)
                {
                    _disconnectRegistration.Dispose();

                    // Complete any ongoing calls to Abort()
                    // If someone calls Abort() later, have it no-op
                    AbortHandler.CompleteAbort();

                    if (_currentRequest != null)
                    {
                        // This will no-op if the request is already finished
                        _currentRequest.Abort();
                    }
                }
            }
        }
Пример #8
0
 public SystemTaskBase GetTask(LoadBalanceWorkload workload, ResourceReservationContext context)
 {
     lock (this.requestQueueLock)
     {
         this.BlockedTaskCount = 0;
         if (this.requests.Count == 0)
         {
             return(null);
         }
         for (int i = 0; i < this.requests.Count; i++)
         {
             IRequest request = this.requests[i];
             if (request.IsBlocked)
             {
                 this.BlockedTaskCount++;
             }
             else if (request.ShouldCancel(this.settings.IdleRunDelay))
             {
                 request.Abort();
                 DatabaseRequestLog.Write(request);
                 this.requests.RemoveAt(i);
                 i--;
             }
             else
             {
                 ResourceKey         obj2;
                 ResourceReservation reservation = context.GetReservation(workload, request.Resources, out obj2);
                 if (reservation != null)
                 {
                     this.requests.RemoveAt(i);
                     return(new LoadBalanceTask(workload, reservation, request));
                 }
                 if (ProcessorResourceKey.Local.Equals(obj2))
                 {
                     this.BlockedTaskCount = this.requests.Count;
                     break;
                 }
                 this.BlockedTaskCount++;
             }
         }
     }
     return(null);
 }
Пример #9
0
        private void OpenConnection(IConnection connection,
                                    string data,
                                    CancellationToken disconnectToken,
                                    Action initializeCallback,
                                    Action <Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool reconnecting    = initializeCallback == null;
            var  callbackInvoker = new ThreadSafeInvoker();
            var  requestDisposer = new Disposer();

            var url = (reconnecting ? connection.Url : connection.Url + "connect") + GetReceiveQueryString(connection, data);

            connection.Trace(TraceLevels.Events, "SSE: GET {0}", url);

            HttpClient.Get(url, req =>
            {
                _request = req;
                connection.PrepareRequest(_request);

                _request.Accept = "text/event-stream";
            }).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    Exception exception = task.Exception.Unwrap();
                    if (!ExceptionHelper.IsRequestAborted(exception))
                    {
                        if (errorCallback != null)
                        {
                            callbackInvoker.Invoke((cb, ex) => cb(ex), errorCallback, exception);
                        }
                        else if (reconnecting)
                        {
                            // Only raise the error event if we failed to reconnect
                            connection.OnError(exception);

                            Reconnect(connection, data, disconnectToken);
                        }
                    }
                    requestDisposer.Dispose();
                }
                else
                {
                    var response  = task.Result;
                    Stream stream = response.GetStream();

                    var eventSource = new EventSourceStreamReader(connection, stream);

                    bool retry = true;

                    var esCancellationRegistration = disconnectToken.SafeRegister(state =>
                    {
                        retry = false;

                        ((IRequest)state).Abort();
                    },
                                                                                  _request);

                    eventSource.Opened = () =>
                    {
                        // If we're not reconnecting, then we're starting the transport for the first time. Trigger callback only on first start.
                        if (!reconnecting)
                        {
                            callbackInvoker.Invoke(initializeCallback);
                        }
                        else if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
                        {
                            // Raise the reconnect event if the connection comes back up
                            connection.OnReconnected();
                        }
                    };

                    eventSource.Message = sseEvent =>
                    {
                        if (sseEvent.EventType == EventType.Data)
                        {
                            if (sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase))
                            {
                                return;
                            }

                            bool timedOut;
                            bool disconnected;
                            TransportHelper.ProcessResponse(connection, sseEvent.Data, out timedOut, out disconnected);

                            if (disconnected)
                            {
                                retry = false;
                                connection.Disconnect();
                            }
                        }
                    };

                    eventSource.Closed = exception =>
                    {
                        if (exception != null)
                        {
                            // Check if the request is aborted
                            bool isRequestAborted = ExceptionHelper.IsRequestAborted(exception);

                            if (!isRequestAborted)
                            {
                                // Don't raise exceptions if the request was aborted (connection was stopped).
                                connection.OnError(exception);
                            }
                        }
                        requestDisposer.Dispose();
                        esCancellationRegistration.Dispose();
                        response.Dispose();

                        if (AbortResetEvent != null)
                        {
                            AbortResetEvent.Set();
                        }
                        else if (retry)
                        {
                            Reconnect(connection, data, disconnectToken);
                        }
                    };

                    eventSource.Start();
                }
            });

            var requestCancellationRegistration = disconnectToken.SafeRegister(state =>
            {
                if (state != null)
                {
                    // This will no-op if the request is already finished.
                    ((IRequest)state).Abort();
                }

                if (errorCallback != null)
                {
                    callbackInvoker.Invoke((cb, token) =>
                    {
#if NET35 || WINDOWS_PHONE
                        cb(new OperationCanceledException(Resources.Error_ConnectionCancelled));
#else
                        cb(new OperationCanceledException(Resources.Error_ConnectionCancelled, token));
#endif
                    }, errorCallback, disconnectToken);
                }
            }, _request);

            requestDisposer.Set(requestCancellationRegistration);

            if (errorCallback != null)
            {
                TaskAsyncHelper.Delay(ConnectionTimeout).Then(() =>
                {
                    callbackInvoker.Invoke((conn, cb) =>
                    {
                        // Abort the request before cancelling
                        _request.Abort();

                        // Connection timeout occurred
                        cb(new TimeoutException());
                    },
                                           connection,
                                           errorCallback);
                });
            }
        }