Ejemplo n.º 1
0
    private void StartListen()
    {
        // Start the receive task, that will remain running for the whole connection
        System.Threading.CancellationToken ct = stopServerTokenSource.Token;
        var task = System.Threading.Tasks.Task.Factory.StartNew(() =>
        {
            ct.ThrowIfCancellationRequested();
            while (true)
            {
                try
                {
                    System.Threading.Tasks.Task <Response> receiveTask = ReceiveMessage();
                    receiveTask.Wait();

                    if (receiveTask.Result.MessageId == Messages.EVENT)
                    {
                        ProcessEvent(receiveTask.Result);
                    }
                    else if (taskCompletion != null)
                    {
                        taskCompletion.SetResult(receiveTask.Result);
                    }
                    else
                    {
                        throw new ErrorException("Received WAMP message that we did not expect.");
                    }

                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }
                }
                catch (System.Exception e)
                {
                    if (e.InnerException.GetType() == typeof(System.Net.WebSockets.WebSocketException))
                    {
                        var exception = e.InnerException as System.Net.WebSockets.WebSocketException;
                        if (exception.WebSocketErrorCode == System.Net.WebSockets.WebSocketError.ConnectionClosedPrematurely)
                        {
                            if (taskCompletion != null)
                            {
                                taskCompletion.SetException(e);
                            }

                            OnDisconnect();

                            return;
                        }
                    }

                    if (ws.State != System.Net.WebSockets.WebSocketState.Open)
                    {
                        OnDisconnect();
                        return;
                    }


                    // Signal the exception to the other thread and continue to listen
                    if (taskCompletion != null)
                    {
                        taskCompletion.SetException(e);
                    }
                }
            }
        }, stopServerTokenSource.Token);
    }
Ejemplo n.º 2
0
#pragma warning restore CA1707  // Remove the underscores from member name
#pragma warning restore SA1300  // Element should begin with an uppercase letter
#pragma warning restore IDE1006 // Naming Styles

        /// <summary>
        /// Transitions the underlying task into the <see cref="SystemTasks.TaskStatus.RanToCompletion"/> state.
        /// </summary>
        public static void SetResult(SystemTaskCompletionSource tcs) => tcs.SetResult();