C#线程调度程序

时间:2010-02-26 00:42:38

标签: c# wpf

我在View(Window)中声明了一个委托函数。

委托函数在另一个类中执行。但是当我运行应用程序并调用委托函数时,我得到以下错误:

  

异常类型:   System.invalidoperationException

     

异常来源:WindowBase

     

异常堆栈跟踪:   System.Windows.threading.dispatcher.VerifyAcess()   System.Windows.Threading.DispatcherObject.VerifyAccess()   System.windows.Media.visual.verifyAPIReadWrite()   ....

1 个答案:

答案 0 :(得分:2)

这意味着在一个线程中运行的函数正在访问由另一个线程“拥有”的DispatcherObject。 DispatcherObjects(包括DependencyObjects,如Visuals)只能从创建它们的线程中访问。所以我猜你在不同的线程上运行你的委托,例如通过线程池或BackgroundWorker。

解决方案是在访问Visual的属性或方法时使用Dispacther.Invoke或BeginInvoke。例如:

private void ThreadMethod()
{
  // ...this is running on a thread other than the UI thread...
  _myVisual.Dispatcher.Invoke(DoSomethingWithMyVisual);
}

private void DoSomethingWithMyVisual()
{
  // because it has been called via Invoke, this will run on the UI thread
  _myVisual.PartyOn();
}
相关问题