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」行で次の例外が発生します。

「閉じられたストリームにアクセスできません。

上記のコードでストリームを閉じたことは理解していますが、終了する前に _cache.Add() が (シリアライゼーションを介して) コピーを作成していませんか? ストリームをシリアル化する正しいプロセスは何ですか?

ありがとう!

4

2 に答える 2

9

問題は、ブロックDispose()の終わりでストリームが(を介して)閉じられることです。using閉じたストリームへの参照を保持します。

代わりに、ストリームの内容をキャッシュに保存します。

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

コンストラクターを呼び出すときは、そのバイト配列から読み取るPngBitmapDecoderために新しいものを作成する必要があります。MemoryStream

于 2010-02-25T04:56:05.050 に答える
6

しかし、_cache.Add()は、終了する前に(シリアル化を介して)コピーを作成していませんか?

必ずしも。「処理中」の場合は、オブジェクト参照を保存するだけです。Streamとにかく実際にはあまりシリアル化できません(aStreamはホースであり、バケットではありません)。

あなたはBLOBを保存したい-ではなくStream

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

...

byte[] blob = _cache.GetData(someId);
if(blob != null) {
    using(Stream inStream = new MemoryStream(blob)) {
         // (read)
    } 
}
于 2010-02-25T04:55:29.903 に答える