0

I have a problem creating an Image in a background-thread. I have a main-icon (16x16 pixel) that should be merged with other icons, that can be an overlay. My code for this is this:

private void GenerateConnectionIcon()
{
    var dGr = new DrawingGroup();

    var newGroupItem = new ImageDrawing(_ConnectionIcon, new Rect(0, 0, 16, 16));
    newGroupItem.Freeze(); //Here it throws the expection

    dGr.Children.Add(newGroupItem);

    foreach (var anOverlay in _ConnectionIconOverlays)
    {
        dGr.Children.Add(new ImageDrawing(anOverlay, new Rect(0, 0, 16, 16)));
    }

    dGr.Freeze();
    var finalIcon = new DrawingImage(dGr);

    finalIcon.Freeze();

    _ConnectionIconMerged = finalIcon;
}

The code quits in the third line because the calling thread is not the owner of the object. I am a little bit confused about this, because the object is created one line above. The variable _ConnectionIcon is an ImageSource and is freezed.

The exact error message is The calling thread cannot access this object because a different thread owns it.

Why I cannot freeze an object, that is created one line above?

kennyzx
  • 12,845
  • 6
  • 39
  • 83
Hunv
  • 385
  • 7
  • 17
  • Search SO for `The calling thread cannot access this object because a different thread owns it` and you will find a plethora of information about how to fix this (hint: `Dispatcher.Invoke()`) – Peter Duniho Oct 23 '14 at 16:22
  • What's `_ConnectionIcon`? – Dour High Arch Oct 23 '14 at 17:00
  • @DourHighArch as described: it is an ImageSource and contains the "base"-Image with a size of 16x16. – Hunv Oct 23 '14 at 17:58
  • @PeterDuniho if I put it in a Dispatcher.Invoke(new Action(() => newGroupItem.Freeze()); the newGroupItem.Freeze() still throws this error – Hunv Oct 23 '14 at 17:59
  • OK, got it: Its really important to use Dispatcher.Invoke(...). I used newGroupItem.Dispatcher.Invoke(...) before. – Hunv Oct 23 '14 at 21:30

0 Answers0