Threading with WPF Images (System.InvalidOperationException)

后端 未结 2 935
不知归路
不知归路 2021-01-25 06:17

I\'m using a thread to get an image from a website and shoot it back to the parent form (WPF) to display. I ran into an issue and have managed to debug it to this example:

相关标签:
2条回答
  • 2021-01-25 06:33

    Most objects in WPF are of this category: they cannot be shared between different threads. However certain low-level resources such as brushes and bitmaps are derived from a special class called Freezable that if frozen can be shared between different threads. Of course once an object is frozen is can no longer be modified in any way. To freeze a freezable object simply call Freeze and this will prevent cross-thread exceptions.

    0 讨论(0)
  • 2021-01-25 06:50

    Instead of

    if (!this.imgVideo.Dispatcher.CheckAccess())
      {
        SetImageCallback del = new SetImageCallback(SetImage);
        this.Dispatcher.Invoke(del, bmp, bmpImg);
      }
    

    try using :

    if (!App.Current.Dispatcher.CheckAccess())
                    App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action<CustomObject>(SetImage),CustomeObjectInstance );
    

    Here Cutom object will be a wrapper class wrapping

    Bitmap bmp, BitmapImage bmpImg
    

    Obviously, your SetImage signature will change to

    SetImage(CutomObject custObj)
    

    I have not tested the code but this may solve the issue. Let us know if this works so that some poor soul can be benefitted from this post. All the best! Sid

    0 讨论(0)
提交回复
热议问题