Boggy
Boggy
CC#
Created by Boggy on 7/12/2024 in #help
C# event subscription in the context of a gRPC stream
I'm trying to understand why my code is not working in the context of a gRPC streaming method.
C#
public override async Task Stream(...)
{
await _myService.DoSomeSubscription();
}
C#
public override async Task Stream(...)
{
await _myService.DoSomeSubscription();
}
When calling DoSomeSubscription() from a singleton service, not a gRPC server service, the code works as expected. The issue is that MyService (singleton) behaves differently if injected into a gRPC service vs a normal singleton service. I narrowed down the issue to the event subscription itself.
C#
public Task DoSomeSubscription()
{
return Task.Run(() =>
{
// my object is also injected as a singleton;
// the subscription looks like it's not made
myObj.Changed += (c) =>
{
Console.WriteLine(c);
};

// this triggers the event, but it never enters the subscription above if the method is called from the gRPC service
// it enters from the normal singleton service
myObj.Change(3);
};
}
C#
public Task DoSomeSubscription()
{
return Task.Run(() =>
{
// my object is also injected as a singleton;
// the subscription looks like it's not made
myObj.Changed += (c) =>
{
Console.WriteLine(c);
};

// this triggers the event, but it never enters the subscription above if the method is called from the gRPC service
// it enters from the normal singleton service
myObj.Change(3);
};
}
I'm not sure what the exact issue is,but my guess is that gRPC somehow works differently behing the scenes, since it has a different threading model.
4 replies