使用新线程的用户控件

时间:2018-12-16 21:50:30

标签: c# multithreading winforms user-controls

我想创建一个名为UserControl的{​​{1}},该实例在加载新线程时实例化一个新线程,并具有一个包含游戏图形的GameControl。 新线程将在while循环中运行,以更新Panel并调用GameObjects重新粉刷面板。

panel1.Invalidadte()

我将控件放在public partial class GameControl : UserControl { int posX = 0; DemoState demoState = DemoState.run; //Threading public delegate void DelegateDemo(); ThreadStart threadStart; Thread runDemoThread; public GameControl(String config) { InitializeComponent(); /*InitizalizNewGameObjects(config);*/ } private void GameControl_Load(object sender, EventArgs e) { threadStart = new ThreadStart(StartThread); runDemoThread = new Thread(threadStart); runDemoThread.Name = "DemoThread"; runDemoThread.Start(); } private void StartThread() { var delegateDemo = new DelegateDemo(RunDemo); this.panel1.BeginInvoke(delegateDemo); } private void RunDemo() { while (demoState != DemoState.stop) { Thread.Sleep(500); switch (demoState) { case DemoState.run: /*UpdateGameObjects();*/ posX++; break; default: demoState = DemoState.stop; break; } panel1.Invalidate(); } } private void panel1_Paint(object sender, PaintEventArgs e) { //Daw posX's value in the panel String drawString = Thread.CurrentThread.Name + " " + posX.ToString(); Font drawFont = new Font("Arial", 16); SolidBrush drawBrush = new SolidBrush(Color.Black); float x = 150.0F; float y = 50.0F; StringFormat drawFormat = new StringFormat(); drawFormat.FormatFlags = StringFormatFlags.DirectionVertical; e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat); /*DrawGameObejects(e);*/ } } 中,并像下面这样将其添加到TabPage:

Form1

我应该在屏幕上看到越来越多的数字,但我得到的只是0,并且程序冻结了,我进行了一些测试,得出的结论是,它等待线程完成。 我尝试使用private void starToolStripMenuItem_Click(object sender, EventArgs e) { if (demo!=null) { return; } demo = new GameControl(RichTextboxNewConfig.Text); TabPageDemo.Controls.Add(demo); } Task,但得到相同的结果。 我在做什么错了?

0 个答案:

没有答案