无法访问封闭流

moo*_*ogs 10 .net c# serialization caching-application-block

我正在尝试使用缓存应用程序块来缓存一些图像(这些图像需要很长时间才能渲染)

  BitmapSource bitmapSource; ///some bitmap source already created
  _cache ///  Caching Application Block
  String someId; //id for this image, used as the key for the cache

  using (var stream = new MemoryStream())
    {
        PngBitmapEncoder encoder = new PngBitmapEncoder();
        encoder.Interlace = PngInterlaceOption.On;
        encoder.Frames.Add(BitmapFrame.Create(bitmapSource));             
        encoder.Save(stream);
        _cache.Add(someId, stream);
    }
Run Code Online (Sandbox Code Playgroud)

然后使用以下方法加载它们

imStream = (Stream)_cache.GetData(someId));
if (imStream != null)
{
    PngBitmapDecoder decoder = new PngBitmapDecoder(imStream,  BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
    return decoder.Frames[0];  //return the bitmap source
}
Run Code Online (Sandbox Code Playgroud)

但在加载过程中,我在"新的PngBitmapDecoder"行中得到以下异常:

"无法访问封闭的流.

我理解我在上面的代码中关闭了流,但是在退出之前是不是_cache.Add()制作副本(通过序列化)?序列化流的正确过程是什么?

谢谢!

Ben*_*n M 9

问题是流Dispose()using块的末尾被关闭(通过).您保留对已关闭流的引用.

而是将流的内容保存到缓存中:

_cache.Add(someId, stream.ToArray());
Run Code Online (Sandbox Code Playgroud)

当您调用PngBitmapDecoder构造函数时,您将必须创建一个新的MemoryStream以从该字节数组中读取.


Mar*_*ell 6

但是_cache.Add()在退出之前是不是制作了一个副本(通过序列化)?

不必要.如果它是"进行中"它将只存储对象引用; Stream无论如何都不是非常可序列化的(a Stream是软管,而不是桶).

你想存储BLOB - 而不是Stream:

    _cache.Add(someId, stream.ToArray());

...

byte[] blob = _cache.GetData(someId);
if(blob != null) {
    using(Stream inStream = new MemoryStream(blob)) {
         // (read)
    } 
}
Run Code Online (Sandbox Code Playgroud)

  • @moogs - 实际上这是第一次进入(04:55:29 vs 04:46:05). (2认同)