Exemplo n.º 1
0
        internal static ResponseClient Start(INetworkClient networkClient)
        {
            var client = new ResponseClient(networkClient);

            client.StartReceiving();
            return(client);
        }
        private void ReceiveMessagesFor(INetworkClient networkClient)
        {
            var task = Task.Run(
                async() =>
            {
                var client        = ResponseClient.Start(networkClient);
                await using var _ = client.ConfigureAwait(false);
                while (_cancellationTokenSource.IsCancellationRequested == false)
                {
                    try
                    {
                        var requestPayload = await client
                                             .ReadAsync(_cancellationTokenSource.Token)
                                             .ConfigureAwait(false);

                        if (!_subscriptions.TryGetValue(
                                requestPayload.Message.GetType(),
                                out var subscription))
                        {
                            throw new InvalidOperationException(
                                $"Missing subscription for {requestPayload.Message.GetType()}");
                        }

                        var response = await subscription(
                            requestPayload.Message,
                            _cancellationTokenSource.Token);

                        await client
                        .SendAsync(
                            new ResponsePayload(
                                requestPayload,
                                new ResponseHeader(requestPayload.Header.Version)
                                .WithCorrelationId(requestPayload.Header.CorrelationId),
                                response),
                            _cancellationTokenSource.Token)
                        .ConfigureAwait(false);
                    }
                    catch when(_cancellationTokenSource.IsCancellationRequested)
                    {
                        return;
                    }
                }
            });

            _backgroundTasks.Add(task);
        }