1

Getting hit with a OutOfMemoryException unhandled.

using(var httpclient = new HttpClient(httpClientHandler))
{
    httpclient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
    httpclient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));

    var request = new HttpRequestMessage(HttpMethod.Post, url);
    request.Content = new FormUrlEncodedContent(parameters);

    var response = await httpclient.SendAsync(request);
    var contents = await response.Content.ReadAsStringAsync();

    var source = contents.ToString();
    return source;
}

I'm not really sure what to do, or what is the specific cause, I believe it has something to do with " await response.Content.ReadAsStringAsync();

someone suggested to use

  ReadAsStreamAsync();

instead and output to a file, however I need to output as a string to " source " so I can analyse the data in another function..

I would also like to add I'm running threads..

Is it possible the

Response.Content

is being stored in the memory even after it has finished that specific function? Do i need to dispose/clear memory or contents after I've returned it to source?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Hostd
  • 25
  • 2
  • 8
  • You may want to read up on "chunked transfer": [HttpClient throws OutOfMemory exception when TransferEncodingChunked is not set](https://stackoverflow.com/q/39973689/215552) – Heretic Monkey Feb 21 '19 at 20:32
  • @HereticMonkey will take a look into that thanks – Hostd Feb 21 '19 at 20:34
  • You might also want to read up on whether it's appropriate to immediately `Dispose` your `HttpClient` like you are doing with your `using` statement. The general consensus is "yes, they are disposable, but, really, you want to hang on to them for a long time, re-using them". There's lots of discussion (on SO and elsewhere) about this. – Flydog57 Feb 21 '19 at 20:47

1 Answers1

0

The advised solution is correct. it seems that the OS memory which your application is hosted on does not have enough memory. In order to workaround this It is wise to write stream as file to disk instead of memory. TransferEncodingChunked may also help but sender need to support it.

using (FileStream fs = File.Create("fileName.ext")
{
    ....
    var stream = await response.Content.ReadAsStreamAsync();
    await fs.CopyToAsync(stream);
    fs.Close();
}
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72