Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

So I am making a simple brick breaking game in c#/wpf. I am running into an issue using timers, I feel like it is probably a simple fix but here is whats happening. Whenever t_Elapsed is fired it attempts to call Update() but when it does its like OMG Im not in the right thread so I cant do that sir. How do I invoke the method from the Game from the proper thread? (And yes I know the code is ugly and has magic numbers but I just kinda chugged it out without putting a lot of effort in. And yes I have zero experience programming games)

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();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use the DispatcherTimer object instead, it will ensure that the timer events are published to the correct thread.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...