how to cancel a server from client with grpc in c#?

174 views Asked by At

I want to cancel a server created in C# from a client written in C#. However, I will not use cancellation tokens for this. I tried to do it with the help of a flag. I wrote a code that sends true when I want to stop sending false while running from the client side. However, when true on the server side, it immediately becomes false again and never exits the while loop. I couldn't solve this problem somehow. can you help me?

public override async Task StreamArrays(MyRequest request, IServerStreamWriter<MyResponse> responseStream, ServerCallContext context)
        {
            try
            {
                while (request.IsCancelledRequested == false)
                {
                    MyResponse response = new MyResponse();
                    counter++;
                    response.data = counter;
                    await responseStream.WriteAsync(response);
                    await Task.Delay(15);
                }
            }
            finally
            {
                request.IsCancelledRequested = true;

            }
        }
        //client;

        public async Task SendStreamArray() // for start
        {
            MyRequest request = new MyRequest()
            {

                IsCancelledRequested = false,

            };
            using var responseStreamArray = client.StreamArrays(request);
            await foreach (var response in responseStreamArray.ResponseStream.ReadAllAsync())
            {
                data = response.data;

            }
        }

        public async void StopStream()
        {
            MyRequest request = new MyRequest()
            {

                IsCancelledRequested = true,

            };
            using var responseStreamArray = client.StreamArrays(request);
        }
0

There are 0 answers

Related Questions in GRPC-C#