0

I have a Web App and I noticed that after a while it restarts due to lack of memory.

After researching, I found that memory increases after sending a message via WebPubSub.

This can be easily reproduced (sample):

using Azure.Core;
using Azure.Messaging.WebPubSub;

var connectionString = "<ConnectionString >";
var hub = "<HubName>";

var serviceClient = new WebPubSubServiceClient(connectionString, hub);
Console.ReadKey();
Task[] tasks = new Task[100];
for (int i = 0; i < 100; i++)
{
    tasks[i] = serviceClient.SendToUserAsync("testUser", RequestContent.Create("Message"), ContentType.TextPlain);
}

Task.WaitAll(tasks);
Console.ReadKey();

During debugging, I noticed that a new HttpConnection is created during each send and the old one remains. Thus, when sending 100 messages, 100 connections will be created, during the next sending, more will be created.

Memory profiler Memory profiler. Heap diff

I concluded that the problem is in the WebPubSub SDK, but maybe it's not so and someone can help me solve it.

UPD:

When sending 100 messages in parallel, 100 connections are created in the HttpConnectionPool, hence the sharp increase in unmanaged memory. The next time you send 100 messages, existing connections from the pool will be used, and no new connections are created, but a lot of data is allocated on the heap.

So now I'm finding out how long connections live in the pool, what data lives in the Heap and how to free them. Call GC.Collect(); after Task.WaitAll(tasks); solves the problem.

Memory profiler

Oleksandr
  • 81
  • 2
  • 12

1 Answers1

0

Both Response and RequestContent are IDisposable.

Does using below code help?

var serviceClient = new WebPubSubServiceClient(connectionString, hub);

Task[] tasks = new Task[100];
for (int i = 0; i < 100; i++)
{
    tasks[i] = SendToUser(serviceClient);
}

Task.WaitAll(tasks);
Console.ReadKey();

private async static Task SendToUser(WebPubSubServiceClient serviceClient)
{
     using var content = RequestContent.Create("Message");
     using var response = await serviceClient.SendToUserAsync("testUser", content, ContentType.TextPlain);
}
vicancy
  • 323
  • 3
  • 11