Closed Alezy80 closed 1 month ago
This problem is caused by the existence of a cache of methods inside GrpcChannel
.
MagicOnionClient.Create
generates a method each time it creates a client for the purpose of binding a serializer/marshaller.
MagicOnionClient
has a method called WithOptions
that returns a client with different options only. This client shares the same methods as the original client.
private static async Task Main(string[] args)
{
// Connect to the server using gRPC channel.
var channel = GrpcChannel.ForAddress("http://localhost:5000");
var ci = channel.CreateCallInvoker();
var client = MagicOnionClient.Create<IMyFirstService>(ci); // <-- Create a client only once.
while (true)
{
var clientWithOptions = client.WithOptions(...); // <-- Create a client with new options here.
var result = await clientWithOptions.SumAsync(123, 456);
Debug.Assert(result == 123 + 456);
}
}
The next example not real production code, but written to reproduce memory leak faster. I have one GRPC channel to which I've connect some clients like this:
GRPC channel not recreated, because it stated
Clients are cached in many situations, but sometimes I need to create a new client with custom headers or set default timeout. Each client adds many objects to
GrpcChannel
. After a few seconds of client running the many new objects are created:Moving
GrpcChannel
creation intowhile
cycle solves leakage problem, but at the cost of performance.Project for reproduce error with client and server: MagicOnionLeak.zip