调用线程不能访问这个对象,因为不同的线程拥有它

问题描述:

所以我在c#/ wpf中做了一个简单的破砖游戏。我遇到了一个使用计时器的问题,我觉得这可能是一个简单的修复,但这里是最新发生的事情。每当t_Elapsed被触发时,它会尝试调用Update(),但是当它像OMG Im那样不在正确的线程中时,我不能做那个先生。我如何从正确的线程从游戏中调用方法? (是的,我知道代码是丑的,有魔力的数字,但我只是有点喝着它无需投入大量的精力,而且是的,我有零个经验游戏编程)调用线程不能访问这个对象,因为不同的线程拥有它

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

'OMG我不是在正确的线程,所以我不能做到这一点sir.' Laserbeak43 2012-10-21 10:10:38

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

+0

略有不同的API。像ElapsedTimeEvent现在名为TickEvent。但是在迁移到新的API之后,它在UI线程中效果很好!我喜欢.NET因为几乎每一个场合都有一个快速解决方案;) – OneWorld 2013-01-28 13:56:20

定时器已用事件从线程池(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); 
+1

+1 DispatcherTimer没有工作,这是对我的工作 – 2014-06-24 01:07:32

The calling thread cannot access this object because a different thread owns it

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

请问您可以从链接的问题在这里添加更多信息。 – VMAtm 2014-08-18 12:14:49