Ejemplo n.º 1
0
        /// <summary>
        /// Subscribes to the provided selector.
        /// </summary>
        /// <param name="selector">The subscription selector.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        private async Task SubscribeNoConnectAsync(EventSelector selector, CancellationToken cancellationToken = default(CancellationToken))
        {
            // throw if cancelled
            cancellationToken.ThrowIfCancellationRequested();

            // serialize
            string requestMsg = JsonConvert.SerializeObject(new Message()
            {
                Payload = new SubscribeMessage()
                {
                    Selector = selector.ToString()
                },
                Type      = "Subscribe",
                MessageID = Guid.NewGuid()
            });

            // wait for subscription semaphore
            await _subscriptionSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

            try {
                // wait for send semaphore
                await _sendSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

                try {
                    // send to opposing client
                    await _client.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(requestMsg)), WebSocketMessageType.Text, true, cancellationToken)
                    .ConfigureAwait(false);

                    // add to subscriptions
                    lock (_subscriptionList)
                        _subscriptionList.Add(selector.ToString());
                } finally {
                    _sendSemaphore.Release();
                }
            } finally {
                _subscriptionSemaphore.Release();
            }
        }