c# - 无法访问已关闭的流

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

我正在尝试使用 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”行出现以下异常:

"Cannot access a closed Stream.

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

谢谢!

最佳答案

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

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

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

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

关于c# - 无法访问已关闭的流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2331675/

相关文章:

.net - 从非特定的 .NET 应用引用特定于平台的库

c# - 如何反序列化动态Json对象?

c# - 在使用 Linq-to-sql 完成插入之前,如何锁定表以防止写入操作

c# - 如何在C#中搜索类中的字符串

c# - 如何进行服务器端 C# SQL 验证

c# - 缩放 WinForms TableLayoutPanel

.net - C# 3.0 对象初始化中的私有(private) setter 属性

从 IEnumerable<IObservable<string>> 到 IObservable<string> 的 C# 响应式(Reactive)扩展

serialization - 如何使用 Protobuf-Net 序列化 .Net Exceptions?

python - 逆向工程通信协议(protocol)