无法访问关闭的流 [英] Cannot Access Closed Stream
问题描述
我试图用href="http://msdn.microsoft.com/en-us/library/aa480453.aspx">缓存应用程序块来缓存一些图像
的BitmapSource的BitmapSource; ///一些位图源已创建
_cache ///缓存应用程序块
字符串someId; // ID为这一形象,作为密钥缓存
使用(VAR流=新的MemoryStream())
{
PngBitmapEn codeR连接codeR =新PngBitmapEn codeR();
EN coder.Interlace = PngInterlaceOption.On;
EN coder.Frames.Add(BitmapFrame.Create(的BitmapSource));
EN coder.Save(流);
_cache.Add(someId,流);
}
,然后使用加载它们:
imStream =(流)_cache.GetData(someId));
如果(imStream!= NULL)
{
PngBitmapDe codeR德codeR =新PngBitmapDe codeR(imStream,BitmapCreateOptions preservePixelFormat,BitmapCacheOption.Default。);
返回去coder.Frames [0]; //返回位图源
}
但加载过程中,我得到了以下异常时说:新的PngBitmapDe codeR行:
无法访问已关闭的流。
我明白我关在上面code中的数据流,而不是_cache.Add()制作拷贝(通过序列化)在退出前?什么是序列化流的正确方法?
谢谢!
但不_cache.Add()制作拷贝(通过序列化)在退出前?
不一定。如果它是过程,它将只存储对象引用; 流
是不是真的很序列化反正(一流
是一个软管,而不是一个桶)。
您要存储BLOB - 而不是流
:
_cache.Add(someId,stream.ToArray());
...
byte []的BLOB = _cache.GetData(someId);
如果(BLOB!= NULL){
使用(流inStream =新的MemoryStream(BLOB)){
// (读)
}
}
I'm trying to use the Caching Application Block to cache some images (these images take a long time to render)
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);
}
And then load them using:
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
}
But during the load, i get the following exception at that "new PngBitmapDecoder" line:
"Cannot access a closed Stream.
I understand I closed the stream in the above code, but isn't _cache.Add() making a copy (via Serialization) before it exits? What's the correct process of serializing the stream?
THanks!
but isn't _cache.Add() making a copy (via Serialization) before it exits?
Not necessarily. If it is "in process" it will just store the object reference; Stream
isn't really very serializable anyway (a Stream
is a hose, not a bucket).
You want to store the BLOB - not the Stream
:
_cache.Add(someId, stream.ToArray());
...
byte[] blob = _cache.GetData(someId);
if(blob != null) {
using(Stream inStream = new MemoryStream(blob)) {
// (read)
}
}
这篇关于无法访问关闭的流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!