Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
997 views
in Technique[技术] by (71.8m points)

dependency injection - Blazor-server scoped services, closed connections, garbage collection

If I have a scoped service:

services.AddSingleton<MyScopedService>();

And in that service, an HTTP request is made:

HttpClient client = _clientFactory.CreateClient();
StringContent formData = ...;
HttpResponseMessage response = await client.PostAsync(uri, formData);
string data = await response.Content.ReadAsStringAsync();

I read here that for an AddScoped service, the service scope is the SignalR connection.

If the user closes the browser tab before the response is returned, the MyScopedService code still completes.

Could someone explain what happens to that MyScopedService instance? When is it considered out of scope? After the code completes? Is the time until it's garbage collected predictable?

I have a Blazor-server project using scoped dependency injections (fluxor, and a CircuitHandler), and I'm noticing that the total app memory increases with each new connection (obviously), but takes a while (minutes) for the memory to come down after the browser tabs are closed.

Just wondering if this is expected, or if I could be doing something to let the memory usage recover more quickly. Or maybe I'm doing something wrong with my scoped services.

question from:https://stackoverflow.com/questions/65603183/blazor-server-scoped-services-closed-connections-garbage-collection

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Add IDisposeAsync to your service then in your service :

public async ValueTask DisposeAsync() => await hubConnection.DisposeAsync();

This was copied from one of my own libraries I was facing the same issue. GC will not work if there are references to other objects...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...