protected void WebSocketOnMessageReceived(object sender, MessageReceivedEventArgs messageReceivedEventArgs) { OnRawMessageReceived(messageReceivedEventArgs.Message); RealtimeChannelResponse response; RealtimeMessage message; if ((response = RealtimeChannelResponse.Deserialize(messageReceivedEventArgs.Message)) != null) { IRealtimeChannel realtimeChannel = null; lock (this) { if (Channels.ContainsKey(response.ChannelId)) { realtimeChannel = Channels[response.ChannelId]; } } realtimeChannel?.OnChannelResponse(response); OnChannelUpdated(realtimeChannel); } else if ((message = RealtimeMessage.Deserialize(messageReceivedEventArgs.Message)) != null) { OnMessageReceived(message); } }
public async Task OpenChannelAsync(IRealtimeChannel channel, CancellationToken cancellationToken) { var subscriptionMessage = channel.GetSubscriptionMessage(); var myTask = new TaskCompletionSource <SubscribedMessage>(); while (!cancellationToken.IsCancellationRequested) { Task <SubscribedMessage> task; lock (this) { if (OpenChannelCompletionSource == null) { OpenChannelCompletionSource = myTask; break; } task = OpenChannelCompletionSource.Task; } try { await task; } catch { // ignore } } // SubscribeMessage to the event EventHandler <MessageReceivedEventArgs> messagEventHandler = null; messagEventHandler = (sender, args) => { RealtimeMessage message; if ((message = RealtimeMessage.Deserialize(args.Message)) != null) { if (message is SubscribedMessage) { WebSocket.MessageReceived -= messagEventHandler; lock (this) { myTask.TrySetResult(message as SubscribedMessage); } } else if (message is ErrorMessage) { WebSocket.MessageReceived -= messagEventHandler; lock (this) { myTask.TrySetException(new Exception((message as ErrorMessage).Message)); } } } }; WebSocket.MessageReceived += messagEventHandler; // Cancellation token cancellationToken.Register(() => { lock (this) { myTask.TrySetCanceled(); } }); // Send subscription message WebSocket.Send(subscriptionMessage.Serialize()); channel.OnChannelSubscribed(await myTask.Task); lock (this) { OpenChannelCompletionSource = null; if (Channels.ContainsKey(channel.ChannelId)) { Channels[channel.ChannelId] = channel; } else { Channels.Add(channel.ChannelId, channel); } } }