如何解决即使使用 Dispatcher.Invoke:调用线程也无法访问此对象,因为其他线程拥有它
我在某个看起来很容易的地方卡住了....
<Image x:Name="ImageControl" Source="{Binding displayedImage,UpdateSourceTrigger=PropertyChanged }" HorizontalAlignment="Left"
Margin="0,0" Stretch="Fill" VerticalAlignment="Bottom"
Width="800" Height="300" Grid.Column="3" Grid.Row="3" />
并在后台创建数据上下文:
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”
我希望有人知道为什么我仍然收到错误。
谢谢!
一切顺利, 扬
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。