调用线程无法访问此对象,因为另一个线程拥有它

所以我在c#/ wpf中制作一个简单的破砖游戏。 我正在使用计时器遇到一个问题,我觉得这可能是一个简单的修复,但这里发生了什么。 每当t_Elapsed被触发时它会尝试调用Update()但是当它像OMG我那样不在正确的线程中时所以我不能这样做先生。 如何从正确的线程中调用Game中的方法? (是的,我知道代码是丑陋的,并且有很多神奇的数字,但我只是在没有付出太多努力的情况下把它搞砸了。是的,我没有编程游戏的经验)

public partial class Game : Grid { public bool running; public Paddle p; public Ball b; Timer t; public Game() { Width = 500; Height = 400; t = new Timer(20); p = new Paddle(); b = new Ball(); for (int i = 15; i < 300; i += 15) { for (int j = 15; j < 455; j += 30) { Brick br = new Brick(); br.Margin = new Thickness(j, i, j + 30, i + 15); Children.Add(br); } } Children.Add(p); Children.Add(b); p.Focus(); t.AutoReset = true; t.Start(); t.Elapsed += new ElapsedEventHandler(t_Elapsed); } void t_Elapsed(object sender, ElapsedEventArgs e) { if (running) { Update(); } } void Update() { b.Update(); //Error here when Update is called from t_Elapsed event } void Begin() { running = true; b.Initiate(); } } 

您应该使用DispatcherTimer对象,它将确保将计时器事件发布到正确的线程。

计时器已用事件从线程池( http://www.albahari.com/threading/part3.aspx#_Timers )触发一个线程,而不是在UI线程上触发。 您最好的方法是通过以下调用来调用控件的调度程序:

 yourControl.Dispatcher.BeginInvoke( System.Windows.Threading.DispatcherPriority.Normal , new System.Windows.Threading.DispatcherOperationCallback(delegate { // update your control here return null; }), null); 

调用线程无法访问此对象,因为另一个线程拥有它

 this.Dispatcher.Invoke((Action)(() => { ...// your code here. }));