【问题标题】:Cannot Access Closed Stream无法访问已关闭的流
【发布时间】:2011-01-20 20:39:10
【问题描述】:

我正在尝试使用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);
    }

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

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
}

但在加载过程中,我在“new PngBitmapDecoder”行出现以下异常:

“无法访问已关闭的 Stream。

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

谢谢!

【问题讨论】:

    标签: c# .net serialization caching-application-block


    【解决方案1】:

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

    不一定。如果它是“正在进行中”,它将只存储对象引用; Stream 无论如何都不是非常可序列化的(Stream 是软管,而不是水桶)。

    您想要存储 BLOB - 而不是 Stream

        _cache.Add(someId, stream.ToArray());
    
    ...
    
    byte[] blob = _cache.GetData(someId);
    if(blob != null) {
        using(Stream inStream = new MemoryStream(blob)) {
             // (read)
        } 
    }
    

    【讨论】:

    • 谢谢!两个很好的答案,我只是标记了第一个 :) 我喜欢主机/存储桶参考。
    • @moogs - 实际上这个是第一位的(04:55:29 vs 04:46:05)。
    • 这很奇怪......之前这篇文章的“已回答 xx 分钟”更高。嗯。
    • 我向你保证,即使使用 ♦ 我也无法改变这一点。
    【解决方案2】:

    问题是流在using 块的末尾关闭(通过Dispose())。您保留对封闭流的引用。

    相反,将流的内容保存到缓存中:

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

    当您调用PngBitmapDecoder 构造函数时,您必须创建一个新的MemoryStream 来读取该字节数组。

    【讨论】:

      猜你喜欢
      • 2011-12-27
      • 2012-06-11
      • 2021-12-21
      • 2017-01-12
      • 1970-01-01
      • 1970-01-01
      • 2016-03-22
      • 2021-01-08
      • 1970-01-01
      相关资源
      最近更新 更多