while循环中的线程问题 [英] problem with threads in the while loop

查看:454
本文介绍了while循环中的线程问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码有什么问题?

what is problem in the my code?

 private void button1_Click(object sender, EventArgs e)
{
     int i = 0;
     ParameterizedThreadStart start = new ParameterizedThreadStart(gh);
     Thread.CurrentThread.Priority = ThreadPriority.Lowest;

     while (i < 100)
     {
         i++;

         System.Threading.Thread u = new System.Threading.Thread(start);
         u.Priority = ThreadPriority.Highest;
         u.Start(i);
     }
 }


 void gh(object e)
 {
     b = delegate()
     {
         label1.Text = string.Format("Step is :{0}", (int)e);
     };
     Invoke(b);
 }




但是此代码可以正确执行.




but this code execute correctly.

private void button1_Click(object sender, EventArgs e)
{
         ThreadStart start = delegate()
         {
             int i = 0;
             while (i < 100)
             {
                 i++;
                 b = delegate()
                 {
          label1.Text = string.Format("Step is :{0}", i);
                 };
                 Invoke(b);
             }
         };
     System.Threading.Thread u = new System.Threading.Thread(start);
     u.Start();
 }

推荐答案

在第一个示例中,您正在创建100个线程.您不知道它们将以什么顺序执行.

在第二个示例中,您仅创建1个线程.由于while循环是在一个线程中执行的,因此这些步骤将按预期的顺序执行.
In the first example, you are creating 100 threads. You can''t know in which order they will be executed.

In the second example, you are creating only 1 thread. Since the while loop is executed within this one thread, the steps are executed in the expected order.


我可以看到几处错误,但这将有助于您发布错误当您尝试跑步时,您会收到.我首先想到的是,您需要用InvokeRequired块包装label1.Text = call.请参阅 MSDN 文档以了解有关操作方法.
I can see a couple of things wrong, but it would help for you to post the error you receive when you are trying to run. My first thought is that you need to wrap the label1.Text = call with an InvokeRequired block. See the MSDN documentation for how to do that.


正确,如果您希望每个启动线程都使用下一个值i更新标签,则将需要某种形式的同步化,例如WaitForSingleObject.

我不认为您的线程是后台线程,除非您将其设置为后台线程. (例如,"u.IsBackground = true").因此,它通过了"if"检查.

唯一对您有帮助的是Thread.Sleep调用,然后仅在启动的线程在10ms过去之前完成时调用.
Right, if you''re expecting each started thread to update the label with the next value of i, you''re going to need some form of synchonization, like WaitForSingleObject.

I don''t believe your thread is a background thread unless you set it so. (e.g., "u.IsBackground = true"). So it blows through the "if" check.

The only thing helping you here is the Thread.Sleep call, and then only whenever the started thread completes before 10ms passes.


这篇关于while循环中的线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆