急!急!急!c#问题

来源:百度知道 编辑:UC知道 时间:2024/06/05 03:36:49
程序如下:
Thread game;
private void button1_Click(object sender, EventArgs e)
{
this.game = new Thread(new ThreadStart(StartGame));
this.game.Start();
}

delegate void DrawDele();
DrawDele drawDelegate;
void StartGame()
{
while (true)
{
Thread.Sleep(1000);
drawDelegate = new DrawDele(MoveSnake);
this.Invoke(drawDelegate, null);
}
}

Point pt = new Point(100, 0);
void MoveSnake()
{
Label labTemp = new Label();
labTemp.BackColor = Color.Blue;
this.pt.Y += 20;
labTemp.Location = this.pt;
labTemp.Size = new Size(40, 20);
labTemp.BorderStyle = BorderStyle.Fixed3D;
this.

1.为什么StartGame()中直接调用MoveSnake()程序就退出呢?
你现在有三个执行线程知道吗?一个是主线程Main,另外一个是自定义线程game,还有一个是你调用Invoke方法执行的隐藏工作线程。
即使你创建线程game去startgame,但是主线程Main会一直执行下去,所以你程序会退出。解决方法是等待线程game执行完毕。用个AutoResetEvent之类的信号量都可以做到。
2.可不可以不用多少线程实现上述代码功能?
如果你不创建game线程去startgame,会由于你的在startgame里面的for循环而让界面死掉。如果你不调用this.Invoke(drawDelegate, null)来绘图的话程序会出抛一个安全异常,说你调用的对象不是该线程(game)内部创建的。

线程问题,多线程。
Thread.Sleep(1000);//这个去掉就好了。
因为你让线程停止了1秒,意思就是在1秒后你才看的见。

用多线程。