Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法访问关闭的流_C#_.net_Serialization_Caching Application Block - Fatal编程技术网

C# 无法访问关闭的流

C# 无法访问关闭的流,c#,.net,serialization,caching-application-block,C#,.net,Serialization,Caching Application Block,我正在尝试使用缓存一些图像(这些图像需要很长时间渲染) 然后使用以下命令加载它们: imStream = (Stream)_cache.GetData(someId)); if (imStream != null) { PngBitmapDecoder decoder = new PngBitmapDecoder(imStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); retu

我正在尝试使用缓存一些图像(这些图像需要很长时间渲染)

然后使用以下命令加载它们:

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”行中得到以下异常:

“无法访问已关闭的流

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

谢谢

但是_cache.Add()不是在退出之前(通过序列化)进行复制吗

不一定。如果它是“正在处理中”,它将只存储对象引用;
实际上不是很可序列化的(流是软管,而不是桶)

您希望存储BLOB,而不是

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

...

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

问题在于,流在使用块的
末尾被关闭(通过
Dispose()
)。您保留了对已关闭流的引用

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

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

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

谢谢!两个答案都很好,我只标记了第一个:)我喜欢主机/桶引用。@moogs-实际上这一个是第一个(04:55:29 vs 04:46:05)。这太奇怪了xx分钟前回答说“这个职位早些时候更高。嗯,我向你保证,即使♦ 我不能改变。
_cache.Add(someId, stream.ToArray());