반응형
using Grpc.Core;
using Grpc.Net.Client;
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Create a gRPC channel
        using var channel = GrpcChannel.ForAddress("https://localhost:5001");

        // Create a gRPC client
        var client = new YourService.YourServiceClient(channel);

        // Create a cancellation token source
        var cancellationTokenSource = new CancellationTokenSource();

        // Make a gRPC call with streaming response
        var call = client.YourStreamingRpc(new YourRequest());

        // Start reading the streaming response in a separate task
        var readTask = Task.Run(async () =>
        {
            try
            {
                await foreach (var response in call.ResponseStream.ReadAllAsync(cancellationTokenSource.Token))
                {
                    // Process the response here
                    Console.WriteLine($"Received response: {response}");
                }
            }
            catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
            {
                // Handle cancellation
                Console.WriteLine("Streaming response canceled.");
            }
        });

        // Simulate cancellation after a certain delay (e.g., 5 seconds)
        await Task.Delay(TimeSpan.FromSeconds(5));
        cancellationTokenSource.Cancel();

        // Wait for the read task to complete
        await readTask;

        // Shutdown the gRPC channel
        await channel.ShutdownAsync();
    }
}
반응형

+ Recent posts