首先我需要说我是 WPF 和 C# 的菜鸟。 应用程序:创建 Mandelbrot 图像 (GUI) 在这种情况下,我的调度员工作得很好:
private void progressBarRefresh(){
while ((con.Progress) < 99)
{
progressBar1.Dispatcher.Invoke(DispatcherPriority.Send, new Action(delegate
{
progressBar1.Value = con.Progress;
}
));
}
}
尝试使用以下代码执行此操作时,我收到了消息(标题):
bmp = BitmapSource.Create(width, height, 96, 96, pf, null, rawImage, stride);
this.Dispatcher.Invoke(DispatcherPriority.Send, new Action(delegate
{
img.Source = bmp;
ViewBox.Child = img; //vllt am schluss
}
));
我将尝试解释我的程序是如何工作的。 我创建了一个新线程(因为 GUI 不响应)来计算像素和颜色。在此线程(方法)中,计算准备就绪后,我使用 Dispatcher 刷新 ViewBox 中的图像。
当我不将计算放在单独的线程中时,我可以刷新或构建我的图像。
最佳答案
以防万一您希望对象在不同线程之间共享,那么始终在 UI 线程上创建该对象。稍后当您想要访问该对象时,您可以检查您是否有权访问该对象。如果您没有访问权限,请使用 UI 线程访问权限重新调用该函数。示例代码如下:
private void YourMethod()
{
if (Application.Current.Dispatcher.CheckAccess())
{
// do whatever you want to do with shared object.
}
else
{
//Other wise re-invoke the method with UI thread access
Application.Current.Dispatcher.Invoke(new System.Action(() => YourMethod()));
}
}
关于c# - WPF 调度程序 {"The calling thread cannot access this object because a different thread owns it."},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2982498/