wpf - 即使使用 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”
我希望有人知道为什么我仍然会收到错误。
谢谢!
一切顺利,简
解决方案
推荐阅读
- gtk3 - 如何获取 GLib.Settings 的范围
- reactjs - 在 React JS 中动态获取徽章值
- activemq-artemis - 故障转移在静态集群 HA 中不起作用
- logic - 需要获取一个逻辑应用连接器,它可以从消息队列中获取文件路径和文件名
- flutter - 未处理的异常:MissingPluginException
- python - Python Selenium:从 jscontoller 读取数据
- angular - 更新模拟对象会给出未定义的错误
- html - 在同一垂直水平上的 Li 旁边有按钮
- pandas - 如何在熊猫中从对象(16-04-2017)的日期格式更改为(2017-04-16)的日期时间格式?
- python - 如何检查文本字段是否包含在 Python Selenium Webdriver 中按定义的文本输入