开发者

C# thread dispatcher

开发者 https://www.devze.com 2022-12-21 13:01 出处:网络
I have a delegate function declared in the View (Window). The delegate function is executed in a other class. But when i run the application and I the delegate function gets called i get the followin

I have a delegate function declared in the View (Window).

The delegate function is executed in a other class. But when i run the application and I the delegate function gets called i get the following error:

Exception types: System.invalidoperationException

Exception sources: WindowBase

Exception stack traces: System.Windows.threading.dispatcher.VerifyAcess() System.Windows.Threading.DispatcherObject.VerifyAccess开发者_如何学运维() System.windows.Media.visual.verifyAPIReadWrite() ....


This means that a function running in one thread is accessing a DispatcherObject "owned" by a different thread. DispatcherObjects (including DependencyObjects such as Visuals) can only be accessed from the thread where they were created. So I am guessing you are running your delegate on a different thread, e.g. via the thread pool or a BackgroundWorker.

The solution is to use Dispacther.Invoke or BeginInvoke when accessing properties or methods of the Visual. For example:

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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号