首页 > 解决方案 > 即使使用 Dispatcher.Invoke:调用线程也无法访问此对象,因为不同的线程拥有它

问题描述

我被困在某个似乎很容易的地方....

我有一个带有图像控件的视图:

 <Image x:Name="ImageControl" Source="{Binding DisplayedImage, UpdateSourceTrigger=PropertyChanged }" HorizontalAlignment="Left" 
    Margin="0,0,0,0" Stretch="Fill" VerticalAlignment="Bottom" 
     Width="800" Height="300" Grid.Column="3" Grid.Row="3" />

并在后台创建 Datacontext :

public MainWindow()
        {
            InitializeComponent();
            MainViewModel VM = new MainViewModel();
            
            ImageControl.DataContext = VM;
        }

在我的 Viewmodel 中,我拥有该属性以及在后台工作人员上做某事。在后台工作人员中,我引发了一个事件,事件处理程序应该更新应该导致图像更新的属性:

public event EventHandler<NewImageToShowEventArgs> NewImageToShowEvent;

        public class NewImageToShowEventArgs : EventArgs
        {
            public BitmapSource NewImage { get; set; }
            public Bitmap NewImage2 { get; set; }

        }

 public MainViewModel()
        {
            uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
            int Result = GetCamera();
            //MessageBox.Show(Convert.ToString( Result));
            // Assign Each Task with GrabImage helper
            
            Grabbgw.DoWork += DoGrab;
           // Grabbgw.RunWorkerCompleted += GrabWorkerCompleted;
            bgws.Add(Grabbgw);
            

            //assign Events
            NewImageToShowEvent += NewImageToShow;
            StartGrab();
        }
 private void NewImageToShow(object sender, NewImageToShowEventArgs e)
        {
            try
            {
                Application.Current.Dispatcher.Invoke((new Action(() =>
                {
                    //DisplayedImage.Freeze(); // through a different error
                    DisplayedImage = e.NewImage.Clone();
                   // DisplayedImage2 = e.NewImage2;
                })));
                //Task.Factory.StartNew(() => DisplayedImage2 = e.NewImage2, CancellationToken.None, TaskCreationOptions.None, uiScheduler);
                //App.Current.MainWindow.Dispatcher.BeginInvoke(new Action(() =>
                //{

                //    DisplayedImage = e.NewImage.Clone();
                //    DisplayedImage2 = e.NewImage2;
                //}));
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }

        }
 NewImageToShowEventArgs  args = new NewImageToShowEventArgs();
                            args.NewImage = rawImage.bitmapsource.Clone() ;
                            args.NewImage2 = rawImage.bitmap;
                            NewImageToShowEvent?.Invoke(this, args);

我尝试了几件事,但结果都是:“调用线程无法访问此对象,因为不同的线程拥有它。” 我现在搜索了几个小时没有任何结果。我的意思是我尝试了这些建议,但它们并没有解决问题。一般信息:我从相机获取图像作为 Bitmap 或 BitmapSource。

在“输出”窗口中,它会显示其他错误:

抛出的异常:WindowsBase.dll 中的“System.InvalidOperationException”抛出的异常:System.Private.CoreLib.dll 中的“System.InvalidOperationException”

我希望有人知道为什么我仍然会收到错误。

谢谢!

一切顺利,简

标签: wpfmultithreadingdata-bindingthread-safetydispatcher

解决方案


推荐阅读