Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用线程移动PictureBox位置_C#_Multithreading_Visual Studio_Panel_Picturebox - Fatal编程技术网

C# 使用线程移动PictureBox位置

C# 使用线程移动PictureBox位置,c#,multithreading,visual-studio,panel,picturebox,C#,Multithreading,Visual Studio,Panel,Picturebox,我正在创造一个捉鸡蛋的游戏。在我的Panel子类中,我有以下代码 public void startGame() { Thread t = new Thread(new ThreadStart(game)); t.Start(); } private void game() { bool run = true; int level = 1; while (run) {

我正在创造一个捉鸡蛋的游戏。在我的Panel子类中,我有以下代码

public void startGame()
    {
        Thread t = new Thread(new ThreadStart(game));
        t.Start();
    }

private void game()
    {
        bool run = true;

        int level = 1;

        while (run)
        {
            Egg egg = dropper.selectEgg();
            int speed = dropper.getSpeed(level);

            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(delegate { 
                    this.Controls.Add(egg);
                    egg.setInitialLocation(dropper.selectPosition());

                    int x = egg.Location.X;
                    int y = egg.Location.Y;

                    while (y <= 1000)
                    {
                        egg.setCurrentLocation(x, dropper.drop(egg, speed));
                        y = egg.Location.Y;
                    }
                }));
            }
            else
            {
                this.Controls.Add(egg);
                egg.setInitialLocation(dropper.selectPosition());

                int x = egg.Location.X;
                int y = egg.Location.Y;

                while (y <= 1000)
                {
                    egg.setCurrentLocation(x, dropper.drop(egg, speed));
                    y = egg.Location.Y;
                }
            }
            Thread.Sleep(3000);
        }
    }
但不知怎么的,我没有看到任何鸡蛋掉落。我猜这是线程访问PictureBox子类的问题?但我似乎在网上找不到任何解决办法


提前非常感谢。

您可以在主UI线程上调用
drop
。这将快速运行一个循环,该循环将递增
y
,直到大于1000。当循环运行时,用户界面无法更新,因此当
drop
完成时,您将看到屏幕底部的鸡蛋,用户界面可以再次运行其消息循环


解决方案是将
drop
更改为仅递减
y
一次,然后将控制权返回到
游戏
循环。你必须移动
y抱歉,我有点困惑。在drop()中,我只是将其设置为返回y位置。在game()中,我添加了egg.setCurrentLocation()。它仍然不起作用。我现在明白了。稍后我将用答案再次更新代码。非常感谢你!
public int drop(Egg egg, int speed)
    {

        int y = egg.Location.Y;
        y += speed;

        return y;
    }