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);
}
StreamArrayswill actually be called twice and one of which calls never exits.request.IsCancelledRequested = true;in the finally block on the server side? This makes no sense, if it is a request coming from the client, and you are checking the incoming request object already in the try block with an infinite while loop, it will already betruewhen you enter the finally block.SendStreamArrayon the client side where it looks like (we cannot know, we do not see your entire client-side code) you start a stream to the server withclient.StreamArrays(request);and await a response, but then you have another stream initiated in theStopStreamfunction, with a single request? You should also be aware that gRPC services are registered as transient per default in C#, meaning that each new request to a service will create a new instance on the server if not configured differently. I think this will result in 2 streams with your code.