I have a memory leak issue when using httpClient.GetAsync.
In the task manager, the processes stay with a high memory consumption that doesn't get freed.
This is my code:
HttpClient httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromMinutes(2);
try
{
using (var response = await httpClient.GetAsync(fullURL))
{
if (!response.IsSuccessStatusCode)
{
Logger.Default.Error($"error code {(int)response.StatusCode} - {response.StatusCode}");
return null;
}
using (MemoryStream memStream = new MemoryStream())
{
await response.Content.CopyToAsync(memStream);
Logger.Default.Debug($"finished reading response, sized {Math.Round(memStream.Length / Math.Pow(1024, 2), 2)} MB");
}
}
}
catch (TaskCanceledException ex)
{
Logger.Default.Error($"Request timed out. {ex.Message}\n{ex.StackTrace}");
return null;
}
However, when I use httpClient.GetStreamAsync instead, and change:
await response.CopyToAsync(memStream);
To:
await response.Content.CopyToAsync(memStream);
The memory does get released after a few seconds.
But I rather use GetAsync since it provides me information about the status code, which GetStreamAsync doesn't.
I've already tried calling the Garbage collector (GC.Collect(2)) after the object got disposed, but it didn't help.
What am I doing wrong?