Sponsored

Friday, November 20, 2020

Reuse a MemoryStream without Writing to a FileStream

MemoryStream is a very useful class as it allows working with a Stream-like data in memory without having dependencies on any external resources like files, etc. Even though the MemoryStream implements an IDisposable interface it does not actually have any critical resources to dispose of, so, explicitly disposing of a MemoryStream object is not strictly necessary as the .NET memory management will take care of it. This specifics presents an opportunity of reusing the MemoryStream object if needed across multiple code scopes.

To do that safely and efficiently remember these easy tips:

  1. Do not create a MemoryStream object inside a limited size inner scope like a small method, try/catch, if/else or using block as it will be disposed of automatically as soon as the code exists the scope. Instead, if you intend to reuse the object, create it in the most outer scope and pass it around as a reference.
  2. Pass the reusable MemoryStream object as a method argument or a global variable. No need to worry about explicitly disposing of the MemoryStream as it will be disposed of automatically by the .NET memory management when no longer referenced.
  3. As any other Stream, the MemoryStream works with data sequentially. So, when receiving a reference to a MemoryStream object in any code scope remember to position the stream to the beginning as the very first step. Otherwise you risk to be disappointed as your code won't find expected data at the current stream position. You can safely use something like
myMemoryStream.Position = 0;

For more information, read the official documentation here https://docs.microsoft.com/en-us/dotnet/api/system.io.memorystream.

No comments:

Post a Comment