Search code examples
c#protocol-buffersgrpc

Repeating rpc calls doesnt add new objects to a queue


I'm trying to implement a simple gRPC service, where a client can queue up a task to the server. I decided to test out multiple calls, where a client sends multiple request, yet the task count is stuck at 1. To debug more i added a simple counter that should increase whenever the method is called. For some reason both of these are stuck at 1, but it shows that the method has been called multiple times. Am I misunderstading how the gRPC protocol works?

Client code

public async Task SendTaskToSchedulerAsync()
{
    using var channel = GrpcChannel.ForAddress(ClientData.schedulerAddress, new GrpcChannelOptions
    {
        HttpHandler = _handler
    });
    var client = new Scheduler.SchedulerClient(channel);
    var task = new gRPCreq_Task { Type = TaskType.TtGeneratePassword, NLoops = 30, WorkTime = 20 };
    try
    {
        for(int i = 0; i < 10; i++)
        {
            var response = await client.C_SendTaskAsync(task);
            Console.WriteLine($"Server responded with: {response.TaskStatus}");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error communicating with the server: {ex.Message}");
    }
}

Server Code:

 public override async Task<gRPCres_TaskStatus> C_SendTask(gRPCreq_Task request, ServerCallContext context)
 {

     _tasks.Enqueue(request);
     counter++;
     Console.WriteLine($"Queue size: {_tasks.Count}");
     Console.WriteLine($"Counter {counter}");
     return await Task.FromResult(new gRPCres_TaskStatus { TaskStatus = TaskStatus.TsTaskAccepted });
 }

Server Output:
Queue size: 1
Counter 1
Queue size: 1
Counter 1
Queue size: 1
Counter 1
Queue size: 1
Counter 1
Queue size: 1
Counter 1
Queue size: 1
Counter 1
Queue size: 1
Counter 1
Queue size: 1
Counter 1
Queue size: 1
Counter 1
Queue size: 1
Counter 1

Solution

  • Okay I managed to find the answer somewhere. In the Program.cs I needed to add:

    builder.Services.AddSingleton<MyService>();
    

    I think every new call created a new instance of the service before I added the line. I could be wrong though.