无法访问变量,因为它由另一个线程拥有

时间:2017-06-29 00:16:10

标签: c# wpf multithreading

除了这个调用之外,我已经完成了所有工作,无论我如何改变,都会抛出错误。

这是一个用C#编写的WPF应用程序。

我尝试过的事情:

  • 从静态上下文访问
  • 从UI线程访问它 (mainWindow.img)

这是我当前的代码,我在静态上下文中访问它:

        var worker = new Thread(() => RenderBarcodeImage(imageBytes));
        worker.SetApartmentState(ApartmentState.STA);
        worker.Name = "RenderBarcodeImage";
        worker.IsBackground = true;
        worker.Start();
        worker.Join();
        Application.Current.Dispatcher.Invoke(new Action(() =>
        {
            var mainWindow = Application.Current.MainWindow as MainWindow;
            if (mainWindow == null) return;
            mainWindow.PairingBarcodeImage.Stretch = mainWindow.PairingBarcodeImage.Width < MainWindow.img.Width ? Stretch.Uniform : Stretch.None;

            mainWindow.PairingBarcodeImage.Source = MainWindow.img.Source;
            if (mainWindow.PairingBarcodeImage.Source != null)
                mainWindow.SaveBarcodeButton.IsEnabled = true;
        }));

无论每次我尝试访问img它都抛出

  

InvalidOperationException:调用线程无法访问此对象,因为另一个线程拥有它。

如何从另一个线程访问img对象?

0 个答案:

没有答案