C
C#11mo ago
wilbo007

Why does my very simple C# program leak 890MB of RAM?

I'm writing a very simple C# application that downloads dummy data from URLs to test internet speed, I thought i'd make a proof of concept. But unfortunately the program leaks RAM in Release mode
C#
using System.IO;
using System.Net.Http;

Console.WriteLine("Hello, World! v3");

static async Task GetRequest(string url)
{
using (var httpClient = new HttpClient())
{
try
{
using (var response = await httpClient.GetAsync(url))
{
var stream = await response.Content.ReadAsStreamAsync();
await stream.CopyToAsync(Stream.Null);
}
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
}


const string URL_TO_GET = "https://speed.cloudflare.com/__down?measId=0&bytes=50000000";
List<Task> tasks = new List<Task>();
for (int i = 0; i < 8; i++)
{
tasks.Add(GetRequest(URL_TO_GET));
}
await Task.WhenAll(tasks);

Console.WriteLine("Work Complete!");
C#
using System.IO;
using System.Net.Http;

Console.WriteLine("Hello, World! v3");

static async Task GetRequest(string url)
{
using (var httpClient = new HttpClient())
{
try
{
using (var response = await httpClient.GetAsync(url))
{
var stream = await response.Content.ReadAsStreamAsync();
await stream.CopyToAsync(Stream.Null);
}
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
}


const string URL_TO_GET = "https://speed.cloudflare.com/__down?measId=0&bytes=50000000";
List<Task> tasks = new List<Task>();
for (int i = 0; i < 8; i++)
{
tasks.Add(GetRequest(URL_TO_GET));
}
await Task.WhenAll(tasks);

Console.WriteLine("Work Complete!");
Any ideas?
3 Replies
wilbo007
wilbo007OP11mo ago
I have found a solution, instead of using httpClient.GetAsync(url), I should've been using httpClient.GetStreamAsync(url)
Jester
Jester11mo ago
i suggest using the same http client for every request too. you dont want to keep allocating new sockets
Arindam
Arindam11mo ago
Use IHttpClientFactory to reuse your HttpClient objects.
Want results from more Discord servers?
Add your server