Calling Thread must be STA

后端 未结 1 485
温柔的废话
温柔的废话 2021-01-27 16:49

I am trying to simulate a projectile and trying to create the labels in the timed event only once, because it has an object in the parameter which i need to be in the timed even

相关标签:
1条回答
  • 2021-01-27 17:33

    You get this error because it is not allowed to access UI from a background thread (the System.Timers.Timer.Elapsed handler is running on a background thread). This is because all the thread which handle UI in WPF should run in Single Threaded Apartment(STA) for synchronization purpose. And, the background workers do not run in STA.

    Use a DispatcherTimer, instead of a System.Timers.Timer.

    The remark section of the MSDN page outline the difference between the 2 timers.

    If a System.Timers.Timer is used in a WPF application, it is worth noting that the System.Timers.Timer runs on a different thread then the user interface (UI) thread. In order to access objects on the user interface (UI) thread, it is necessary to post the operation onto the Dispatcher of the user interface (UI) thread using Invoke or BeginInvoke.

    Reasons for using a DispatcherTimer opposed to a System.Timers.Timer are that the DispatcherTimer runs on the same thread as the Dispatcher and a DispatcherPriority can be set on the DispatcherTimer.

    0 讨论(0)
提交回复
热议问题