tags:

views:

147

answers:

1

I've come across this code in one of my projects, which has a static function to return a MemoryStream from a file, which is then stored in Cache. Now the same class has a constructor which allows to store a MemoryStream in a private variable and later use it. So it looks like this:

private MemoryStream memoryStream;

public CountryLookup(MemoryStream ms)
{
    memoryStream = ms;
}

public static MemoryStream FileToMemory(string filePath)
{
    MemoryStream memoryStream = new MemoryStream();
    ReadFileToMemoryStream(filePath, memoryStream);

    return memoryStream;
}

Usage:

Context.Cache.Insert("test",
                CountryLookup.FileToMemory(
                    ConfigurationSettings.AppSettings["test"]),
                new CacheDependency(someFileName)
                );

And then:

CountryLookup cl = new CountryLookup(
                ((MemoryStream)Context.Cache.Get("test"))
                );

So I was wondering who should dispose the memoryStream and when? Ideally CountryLookup should implement IDisposable.

Should I even care about it?

+4  A: 

It's slightly ugly - in particular, the MemoryStream is stateful, because it has the concept of the "current position".

Why not just store a byte array instead? You can easily build multiple MemoryStreams which wrap the same byte array when you need to, and you don't need to worry about the statefulness.

MemoryStreams don't usually require disposal, but I personally tend to dispose them out of habit. If you perform asynchronous operations on them or use them in remoting, I believe disposal does make a difference at that point. Byte arrays are just simpler :)

Jon Skeet
+1, to store the `byte[]` array in the cache - instance members of `MemoryStream` are not guaranteed to be thread safe.
Darin Dimitrov