在循环的任何步骤中更改Label.Text [英] Change Label.Text in any step in the loop

查看:73
本文介绍了在循环的任何步骤中更改Label.Text的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在此代码中的任何步骤标签中显示该步骤的编号.
在我的代码中,只需在标签上显示最后一个数字即可.

我也Label.Invalidate()完成了,但是不起作用.

I want in this code in the any step label show the Number of that step.
In the my code just show last number in the label!

I also Label.Invalidate() the done, but do not work.

private void button1_Click(object sender, EventArgs e)
   {
       int i = 0;
       while (i<100)
       {
           i++;
           label1.Text = string.Format("Step is :{0}", i);
           System.Threading.Thread.Sleep(1000);
       }
   }

推荐答案

您的标签无法显示步骤号,因为您的步骤完成得如此之快,以至于最后一个编号是屏幕上唯一一个足够长的编号注册,或者更有可能是因为还处理显示GUI的主线程忙于执行您的步骤,以至于没有时间显示数字.

我会让你猜是怎么回事.

此处 [ ^ ]是一篇大致满足您需求的文章.看看是否可以为您的应用程序改编其中的代码.
Your Label is unable to display the step numbers either because your steps complete so quickly that it the last number is the only one on screen long enough to register, or, more likely, because the main thread, which also deals with displaying the GUI, is so busy doing your steps that it has no time to display the numbers.

I''ll let you guess which is happening.

Here[^] is an article that does roughly what you need. See if you can adapt the code in it for your application.


我已经为另一个问题提供了完整的答案,请参见

逐步更改以显示控件 [ ^ ].

您可以使用BackgroundWorker类.

您试图做的是一个大罪过:1)您正在睡眠时阻塞了UI线程,2)您正在循环中分配属性,但是由于您正在阻塞事件的处理而无法处理主UI循环; DoEvent是很大的禁忌(根据经验).

—SA
I already gave a comprehensive answer to another question, see

Changes step by step to show a control[^].

You can use BackgroundWorker class.

What you''re trying to do is a big sin: 1) your are blocking UI thread with you sleep, 2) you''re assigning property in the loop, but in can not be processed because you are blocking event processing of the main UI loop; DoEvent is a big no-no (as a rule of thumb).

—SA


还有更好的方法,但这是向您展示基础知识的简单方法:
There are better ways, but here is the simple way that will show you the basics:
private void button1_Click(object sender, EventArgs e)
{
    var t = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
    {
        int i = 0;
        while (i < 10)
        {
            i++;
            var ts = new System.Threading.ThreadStart(() =>
            {
                label1.Text = string.Format("Step is: {0}", i.ToString());
            });
            if (this.InvokeRequired)
                this.Invoke(ts);
            else
                ts();
            System.Threading.Thread.Sleep(1000);
        }
    }));
    t.Start();
}


基本上,您可以在与主线程不同的线程上运行代码.这将释放主线程以执行UI更新.每当需要更改UI时,都必须在主线程上调用代码.


Basically, you run your code on a different thread than the main thread. This frees the main thread to perform UI updates. Whenever you need to change the UI, you must invoke your code on the main thread.


这篇关于在循环的任何步骤中更改Label.Text的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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