Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Grpc System.InvalidOperationException: 'Cannot write message after request is complete.'

At runtime I get the following error:

System.InvalidOperationException: 'Cannot write message after request is complete.'

I'm using Grpc and reactive X to get data.

public class SensorService: Protos.Vehicule.VehiculeBase
{

    private readonly ILogger<SensorService> _logger;
    private DataProvider _dataProvider;
    private CarSim.Vehicule _vehicule;

    public SensorService(ILogger<SensorService> logger)
    {
      
        _dataProvider = new DataProvider(new CarSim.Vehicule());
        _vehicule = _dataProvider.getVehicule();
        _logger = logger;
        _dataProvider.Start();
    }

    public System.IObserver<CarSim.Vehicule> GetData { get; private set; }

    public override async Task Status(All request, IServerStreamWriter<StatusVehicule> responseStream, ServerCallContext context)
    {  
        
        while (!context.CancellationToken.IsCancellationRequested)
        {

             _vehicule.VehiculeChangedState.Subscribe(onNext: new Action<CarSim.Vehicule>(async (t) =>
            {
                await responseStream.WriteAsync(new StatusVehicule()
                 {
                     Camera = t.Camera,
                     FuelLevel = t.FuelLevel,
                     GunStatus = true,
                     Light = t.Light,
                     OilLevel = t.OilLevel,
                     Peed = t.Speed,
                    
                     Tempature = t.Tempature
                 }                

                    );
                 
             ; }));
         
        }
    }

    
}

enter image description here

like image 763
Benoit Goethals Avatar asked May 20 '26 03:05

Benoit Goethals


1 Answers

This is likely not a bug. The exception means that you're trying to send a response after the RPC has actually finished. Usually this happens when the RPC deadline is exceeded (at which point the RPC is automatically cancelled) or when it was cancelled by the client. Both of these situations can happen at any time (from the server side handler's perspective) and they are basically an inherent race condition (the RPC could have been cancelled just before you decide to send the response).

The exception is just gRPC's way of informing you that the response could not be sent (and there is really no way to send a response AFTER the RPC has finished).

like image 172
Jan Tattermusch Avatar answered May 22 '26 16:05

Jan Tattermusch