日期:2014-05-18  浏览次数:20798 次

【winform】我想点击button1让Label上显示从0,1,2,3,……,10000000
程序是这样写的:

C# code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace doevent
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i <=10000000; i++)
            {
                label1.Text = i.ToString();
            }
        }
    }
}



为什么我点击button1之后,然后我拖动那个窗口,就会无法响应,而且CPU占用100%,然后我加了一句Application.DoEvents(); 这样可以拖动了,但是CPU还是占了100%....

不知道应该怎么做才能完美啊。。。。

------解决方案--------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace doevent
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

}

private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i <=10000000; i++)
{
label1.Text = i.ToString();
Application.DoEvents();
}
}
}
}


------解决方案--------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Threading;

namespace doevent
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

}

private void button1_Click(object sender, EventArgs e)
{
Thread thr = new Thread(new ThreadStart(aaa));
thr.Start();
}

private void aaa()
{
for (int i = 0; i <=10000000; i++)
{
Thread.Sleep(1);
label1.Text = i.ToString();
}
}
}
}

------解决方案--------------------
你是想让Label的值从0开始每过一秒就加1吧?
这么写肯定不行
用线程或者Timer吧
------解决方案--------------------
你可以考虑时间控件来做~~
------解决方案--------------------
C# code
for (int i = 0; i <=10000000; i++)
{
  label1.Text = i.ToString();
  Application.DoEvents();
  Thread.Sleep(10);
}

------解决方案--------------------
探讨
C# codefor (int i = 0; i <=10000000; i++)
{
label1.Text = i.ToString();
Application.DoEvents();
Thread.Sleep(10);
}

------解决方案--------------------
ThreadStart start = new ThreadStart(test);
Thread t = new Thread(start);
t.Start();

private delegate void InvokeCallback(string msg);
private void test()
{
for (int i = 0; i < 1000000; i++)