开发者

Storing MemoryStream in Cache

开发者 https://www.devze.com 2022-12-09 12:23 出处:网络
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

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",
   开发者_如何学Python             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?


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 :)

0

精彩评论

暂无评论...
验证码 换一张
取 消