当前位置: 首页>>代码示例>>C#>>正文


C# IConnection.ChangeState方法代码示例

本文整理汇总了C#中IConnection.ChangeState方法的典型用法代码示例。如果您正苦于以下问题:C# IConnection.ChangeState方法的具体用法?C# IConnection.ChangeState怎么用?C# IConnection.ChangeState使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IConnection的用法示例。


在下文中一共展示了IConnection.ChangeState方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: FireReconnected

 /// <summary>
 /// 
 /// </summary>
 private static void FireReconnected(IConnection connection)
 {
     // Mark the connection as connected
     if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
     {
         connection.OnReconnected();
     }
 }
开发者ID:RodH257,项目名称:SignalR,代码行数:11,代码来源:LongPollingTransport.cs

示例2: OpenConnection

        private void OpenConnection(IConnection connection, string data, Action initializeCallback, Action<Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool reconnecting = initializeCallback == null;
            var callbackInvoker = new ThreadSafeInvoker();

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

            Action<IRequest> prepareRequest = PrepareRequest(connection);

            #if NET35
            Debug.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, "SSE: GET {0}", (object)url));
            #else
            Debug.WriteLine("SSE: GET {0}", (object)url);
            #endif

            _httpClient.GetAsync(url, request =>
            {
                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);
                        }
                    }
                }
                else
                {
                    IResponse response = task.Result;
                    Stream stream = response.GetResponseStream();

                    var eventSource = new EventSourceStreamReader(stream);
                    bool retry = true;

            #if MONOTOUCH
                    lock(connection.Items)
                    {
            #endif
                        connection.Items[EventSourceKey] = eventSource;
            #if MONOTOUCH
                    }
            #endif

                    eventSource.Opened = () =>
                    {
                        if (initializeCallback != null)
                        {
                            callbackInvoker.Invoke(initializeCallback);
                        }

                        if (reconnecting && connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
                        {
                            // Raise the reconnect event if the connection comes back up
                            connection.OnReconnected();
                        }
                    };

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

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

                            if (disconnected)
                            {
                                retry = false;
                            }
                        }
                    };

                    eventSource.Closed = exception =>
                    {
                        if (exception != null && !ExceptionHelper.IsRequestAborted(exception))
                        {
                            // Don't raise exceptions if the request was aborted (connection was stopped).
                            connection.OnError(exception);
                        }
//.........这里部分代码省略.........
开发者ID:cryophobia,项目名称:SignalR,代码行数:101,代码来源:ServerSentEventsTransport.cs

示例3: Reconnect

 private void Reconnect(IConnection connection, string data)
 {
     // Wait for a bit before reconnecting
     TaskAsyncHelper.Delay(ReconnectDelay).Then(() =>
     {
         if (connection.State == ConnectionState.Reconnecting ||
             connection.ChangeState(ConnectionState.Connected, ConnectionState.Reconnecting))
         {
             // Now attempt a reconnect
             OpenConnection(connection, data, initializeCallback: null, errorCallback: null);
         }
     });
 }
开发者ID:cryophobia,项目名称:SignalR,代码行数:13,代码来源:ServerSentEventsTransport.cs

示例4: OpenConnection

        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);
//.........这里部分代码省略.........
开发者ID:armandoramirezdino,项目名称:SignalR,代码行数:101,代码来源:ServerSentEventsTransport.cs

示例5: PollingLoop

        private void PollingLoop(IConnection connection, string data, Action initializeCallback, Action<Exception> errorCallback, bool raiseReconnect = false)
        {
            string url = connection.Url;

            // This is only necessary for the initial request where initializeCallback and errorCallback are non-null
            int callbackFired = 0;

            if (connection.MessageId == null)
            {
                url += "connect";
            }
            else if (raiseReconnect)
            {
                url += "reconnect";

                if (!connection.ChangeState(ConnectionState.Connected, ConnectionState.Reconnecting))
                {
                    return;
                }
            }

            url += GetReceiveQueryString(connection, data);

            #if NET35
            Debug.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, "LP: {0}", (object)url));
            #else
            Debug.WriteLine("LP: {0}", (object)url);
            #endif

            _httpClient.PostAsync(url, PrepareRequest(connection)).ContinueWith(task =>
            {
                // Clear the pending request
                connection.Items.Remove(HttpRequestKey);

                bool shouldRaiseReconnect = false;
                bool disconnectedReceived = false;

                try
                {
                    if (!task.IsFaulted)
                    {
                        if (raiseReconnect)
                        {
                            // If the timeout for the reconnect hasn't fired as yet just fire the
                            // event here before any incoming messages are processed
                            FireReconnected(connection);
                        }

                        // Get the response
                        var raw = task.Result.ReadAsString();

            #if NET35
                        Debug.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, "LP Receive: {0}", (object)raw));
            #else
                        Debug.WriteLine("LP Receive: {0}", (object)raw);
            #endif

                        ProcessResponse(connection, raw, out shouldRaiseReconnect, out disconnectedReceived);
                    }
                }
                finally
                {
                    if (disconnectedReceived)
                    {
                        connection.Stop();
                    }
                    else
                    {
                        bool requestAborted = false;

                        if (task.IsFaulted)
                        {
                            // Raise the reconnect event if we successfully reconnect after failing
                            shouldRaiseReconnect = true;

                            // Get the underlying exception
                            Exception exception = task.Exception.Unwrap();

                            // If the error callback isn't null then raise it and don't continue polling
                            if (errorCallback != null &&
                                Interlocked.Exchange(ref callbackFired, 1) == 0)
                            {
                                // Call the callback
                                errorCallback(exception);
                            }
                            else
                            {
                                // Figure out if the request was aborted
                                requestAborted = ExceptionHelper.IsRequestAborted(exception);

                                // Sometimes a connection might have been closed by the server before we get to write anything
                                // so just try again and don't raise OnError.
                                if (!requestAborted && !(exception is IOException))
                                {
                                    // Raise on error
                                    connection.OnError(exception);

                                    // If the connection is still active after raising the error event wait for 2 seconds
                                    // before polling again so we aren't hammering the server
                                    TaskAsyncHelper.Delay(_errorDelay).Then(() =>
//.........这里部分代码省略.........
开发者ID:RodH257,项目名称:SignalR,代码行数:101,代码来源:LongPollingTransport.cs

示例6: OpenConnection

        internal void OpenConnection(IConnection connection, string data, CancellationToken disconnectToken, bool reconnecting)
        {
            // If we're reconnecting add /connect to the url
            var url = reconnecting
                ? UrlBuilder.BuildReconnect(connection, Name, data)
                : UrlBuilder.BuildConnect(connection, Name, data);

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

            var getTask = HttpClient.Get(url, req =>
            {
                _request = req;
                _request.Accept = "text/event-stream";

                connection.PrepareRequest(_request);

            }, isLongRunning: true);

            var requestCancellationRegistration = disconnectToken.SafeRegister(state =>
            {
                _stop = true;

                // This will no-op if the request is already finished.
                ((IRequest)state).Abort();
            }, _request);
            
            getTask.ContinueWith(task =>
            {
                if (task.IsFaulted || task.IsCanceled)
                {
                    var exception = task.IsCanceled
                        ? new OperationCanceledException(Resources.Error_TaskCancelledException)
                        : task.Exception.Unwrap(); 

                    if (!reconnecting)
                    {
                        TransportFailed(exception);
                    }
                    else if (!_stop)
                    {
                        // Only raise the error event if we failed to reconnect
                        connection.OnError(exception);

                        Reconnect(connection, data, disconnectToken);
                    }

                    requestCancellationRegistration.Dispose();
                }
                else
                {
                    // If the disconnect token is canceled the response to the task doesn't matter.
                    if (disconnectToken.IsCancellationRequested)
                    {
                        return;
                    }

                    var response = task.Result;
                    Stream stream = response.GetStream();

                    var eventSource = new EventSourceStreamReader(connection, stream);

                    eventSource.Opened = () =>
                    {
                        // This will noop if we're not in the reconnecting state
                        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 &&
                            !sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase))
                        {
                            ProcessResponse(connection, sseEvent.Data);
                        }
                    };

                    eventSource.Closed = exception =>
                    {
                        if (exception != null)
                        {
                            // Check if the request is aborted
                            if (!ExceptionHelper.IsRequestAborted(exception))
                            {
                                // Don't raise exceptions if the request was aborted (connection was stopped).
                                connection.OnError(exception);
                            }
                        }

                        requestCancellationRegistration.Dispose();
                        response.Dispose();

                        if (_stop)
                        {
                            AbortHandler.CompleteAbort();
                        }
                        else if (AbortHandler.TryCompleteAbort())
//.........这里部分代码省略.........
开发者ID:Choulla-Naresh8264,项目名称:SignalR,代码行数:101,代码来源:ServerSentEventsTransport.cs

示例7: Reconnect

        // internal for testing
        internal async Task Reconnect(IConnection connection, string connectionData)
        {
            var reconnectUrl = UrlBuilder.BuildReconnect(connection, Name, connectionData);

            while (TransportHelper.VerifyLastActive(connection) && connection.EnsureReconnecting() && !_disconnectToken.IsCancellationRequested)
            {
                try
                {
                    await StartWebSocket(connection, reconnectUrl);

                    if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
                    {
                        connection.OnReconnected();
                    }

                    break;
                }
                catch (OperationCanceledException)
                {
                    break;
                }
                catch (Exception ex)
                {
                    connection.OnError(ex);
                }

                await Task.Delay(ReconnectDelay);
            }
        }
开发者ID:kietnha,项目名称:SignalR,代码行数:30,代码来源:WebSocketTransport.cs

示例8: OpenConnection

        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);
            IRequest request = null;

            #if NET35
            Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "SSE: GET {0}", (object)url));
            #else
            Debug.WriteLine("SSE: GET {0}", (object)url);
            #endif

            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
                {
                    IResponse response = task.Result;
                    Stream stream = response.GetResponseStream();

                    var eventSource = new EventSourceStreamReader(stream);
                    bool retry = true;

                    var esCancellationRegistration = disconnectToken.SafeRegister(es =>
                    {
                        retry = false;
                        es.Close();
                    }, eventSource);

                    eventSource.Opened = () =>
                    {
                        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 =>
                    {
                        bool isRequestAborted = false;

                        if (exception != null)
//.........这里部分代码省略.........
开发者ID:stirno,项目名称:SignalR,代码行数:101,代码来源:ServerSentEventsTransport.cs

示例9: OpenConnection

        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();
            Action initializeInvoke = () =>
            {
                callbackInvoker.Invoke(initializeCallback);
            };
            var url = connection.Url + (reconnecting ? "reconnect" : "connect") + GetReceiveQueryString(connection, data);

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

            HttpClient.Get(url, req =>
            {
                _request = req;
                _request.Accept = "text/event-stream";

                connection.PrepareRequest(_request);

            }, isLongRunning: true).ContinueWith(task =>
            {
                if (task.IsFaulted || task.IsCanceled)
                {
                    Exception exception;

                    if (task.IsCanceled)
                    {
                        exception = new OperationCanceledException(Resources.Error_TaskCancelledException);
                    }
                    else
                    {
                        exception = task.Exception.Unwrap();
                    }

                    if (errorCallback != null)
                    {
                        callbackInvoker.Invoke((cb, ex) => cb(ex), errorCallback, exception);
                    }
                    else if (!_stop && reconnecting)
                    {
                        // Only raise the error event if we failed to reconnect
                        connection.OnError(exception);

                        Reconnect(connection, data, disconnectToken);
                    }
                    requestDisposer.Dispose();
                }
                else
                {
                    // If the disconnect token is canceled the response to the task doesn't matter.
                    if (disconnectToken.IsCancellationRequested)
                    {
                        return;
                    }

                    var response = task.Result;
                    Stream stream = response.GetStream();

                    var eventSource = new EventSourceStreamReader(connection, stream);

                    var esCancellationRegistration = disconnectToken.SafeRegister(state =>
                    {
                        _stop = true;

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

                    eventSource.Opened = () =>
                    {
                        // This will noop if we're not in the reconnecting state
                        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 shouldReconnect;
                            bool disconnected;
                            TransportHelper.ProcessResponse(connection, sseEvent.Data, out shouldReconnect, out disconnected, initializeInvoke);

                            if (disconnected)
                            {
                                _stop = true;
//.........这里部分代码省略.........
开发者ID:fszlin,项目名称:Nivot.SignalR.Client.Net35,代码行数:101,代码来源:ServerSentEventsTransport.cs

示例10: OpenConnection

        private void OpenConnection(IConnection connection, string data, Action initializeCallback, Action<Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool reconnecting = initializeCallback == null;

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

            Action<IRequest> prepareRequest = PrepareRequest(connection);

            #if NET35
            Debug.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, "SSE: GET {0}", (object)url));
            #else
            Debug.WriteLine("SSE: GET {0}", (object)url);
            #endif

            _httpClient.GetAsync(url, request =>
            {
                prepareRequest(request);

                request.Accept = "text/event-stream";

            }).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    var exception = task.Exception.Unwrap();
                    if (!ExceptionHelper.IsRequestAborted(exception))
                    {
                        if (errorCallback != null &&
                            Interlocked.Exchange(ref _initializedCalled, 1) == 0)
                        {
                            errorCallback(exception);
                        }
                        else if (reconnecting)
                        {
                            // Only raise the error event if we failed to reconnect
                            connection.OnError(exception);
                        }
                    }

                    if (reconnecting)
                    {
                        // Retry
                        Reconnect(connection, data);
                        return;
                    }
                }
                else
                {
                    IResponse response = task.Result;
                    Stream stream = response.GetResponseStream();

                    var eventSource = new EventSourceStreamReader(stream);
                    bool retry = true;

                    connection.Items[EventSourceKey] = eventSource;

                    eventSource.Opened = () =>
                    {
                        if (Interlocked.CompareExchange(ref _initializedCalled, 1, 0) == 0)
                        {
                            initializeCallback();
                        }

                        if (reconnecting && connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
                        {
                            // Raise the reconnect event if the connection comes back up
                            connection.OnReconnected();
                        }
                    };

                    eventSource.Error = connection.OnError;

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

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

                            if (disconnected)
                            {
                                retry = false;
                            }
                        }
                    };

                    eventSource.Closed = () =>
                    {
                        response.Close();

                        if (retry)
                        {
                            Reconnect(connection, data);
//.........这里部分代码省略.........
开发者ID:RodH257,项目名称:SignalR,代码行数:101,代码来源:ServerSentEventsTransport.cs


注:本文中的IConnection.ChangeState方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。