开发者

WPF BitmapFrame and multiple threads

I have a PNG file stored in my cloud in blob storage, I want to download it and render it on the screen in WPF.

I know about the Dispatcher and Freezing, but nothing is working. I keep getting the error about "another thread owns it".

Here is what I have:

var decoder = GetDecoder("http://address/image.png");

Dispatcher.Invoke(DispatcherPriority.Send, new Action<BitmapFrame>(SetImage), decoder.Frames[0]);

public void SetImage(BitmapFrame source)
{
    var bitmapFrame = BitmapFrame.Create(source);  //ERROR HERE!!!!!!!!
    LazyImage.Source = bitmapFrame;
}

private BitmapDecoder GetDecoder(object uri)
{
    var extension = System.IO.Path.GetExtension((string)uri);
开发者_StackOverflow    BitmapDecoder decoder = null;
    if (extension.ToLower() == ".png")
        decoder = BitmapDecoder.Create(new Uri((string)uri, UriKind.Absolute), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
    return decoder;
}

If i try to freeze the Frame[0] I get an exception saying that this Frame cannot be frozen. Also the Decoder returned by BitmapDecoder.Create is not a PngBitmapDecoder but a LateBoundBitmapDecoder which I dont really know how to use effectively.


In brief: try wrapping the result into a WriteableBitmap.

Long story, with code.


Its possible that you need to not only create the Bitmapframe on the dispatcher but also the BitmapDecoder? Have you tried invoking the GetDecoder on the dispatcher?


This is still a problem today! Wrapping the data in WriteableBitmap as suggested by Bohdan will work, but that type has a front and back buffer which doubles its memory footprint. CachedBitmap is a better choice.

new CachedBitmap(bitmapSource, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

Use BitmapCacheOption.OnLoad unless you like surprises, and remember to freeze the resulting object too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜