0

I have a new project with existing code. And I saw that in one method was used a stream without 'using' statement:

 private FileInfoRequest ParseFileInfoRequest(Stream body)
        {
            try
            {
                var sr = new StreamReader(body, Encoding.UTF8);
                return JsonConvert.DeserializeObject<FileInfoRequest>(sr.ReadToEnd());
            }
            catch (Exception ex)
            {
                _log.Error("Could not parse FileInfoRequest", ex);
                throw Thrower.GetThrowError(HttpStatusCode.BadRequest,
                    _localization.Api().BadRequestBody,
                    UiMessageKey.ApiBadRequest);
            }
        }

Question is: will this stream clear by GC or I need to write something like:

            using(sr)
            {
                return JsonConvert.DeserializeObject<FileInfoRequest>(sr.ReadToEnd());
            }
MydrecTeni
  • 47
  • 5
  • 2
    You should dispose of the stream. Yes – Nkosi Jan 30 '18 at 12:33
  • This is an interesting read relating to Dispose and it's impact on Garbage Collection. https://stackoverflow.com/questions/7520881/is-it-bad-practice-to-depend-on-the-net-automated-garbage-collector – Wheels73 Jan 30 '18 at 12:41

1 Answers1

0

Yes, you should always dispose the stream when it is no longer needed. Otherwise there might always be a reference left to this stream and the GC will not remove it from memory.

by either wrapping the code in a using block or using sr.Dispose();.

Jerodev
  • 32,252
  • 11
  • 87
  • 108