C# 窗口无假死,进度条

Posted zishen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 窗口无假死,进度条相关的知识,希望对你有一定的参考价值。

 

 

        DataTable table;
        int currentIndex = 0;
        int max = 10000;


        private void button1_Click(object sender, EventArgs e)
        {
            buttonOK.Enabled = false;
            Thread thread = new Thread(new ThreadStart(LoadData));
            thread.IsBackground = true;
            thread.Start();

            progressBar1.Minimum = 0;
            progressBar1.Maximum = max;
        }
        private void LoadData()
        {
            SetLabelText("数据加载中...");
            currentIndex = 0;
            table = new DataTable();
            table.Columns.Add("id");
            table.Columns.Add("name");
            table.Columns.Add("age");
            while (currentIndex < max)
            {
                SetLabelText(string.Format("当前行:{0},剩余量:{1},完成比例:{2}%",
                    currentIndex, max - currentIndex, (Convert.ToDecimal(currentIndex) / Convert.ToDecimal(max) * 100).ToString()));
                SetPbValue(currentIndex);
                DataRow dr = table.NewRow();
                dr["id"] = currentIndex;
                dr["name"] = "张三";
                dr["age"] = currentIndex + 5;
                table.Rows.Add(dr);
                currentIndex++;
            }

            SetDgvDataSource(table);
            SetLabelText("数据加载完成");

            this.BeginInvoke(new MethodInvoker(delegate()
            {
                buttonOK.Enabled = true;
            }));
        }

        delegate void labDelegate(string str);
        private void SetLabelText(string str)
        {
            if (label1.InvokeRequired)
            {
                Invoke(new labDelegate(SetLabelText), new string[] { str });
            }
            else
            {
                label1.Text = str;
            }
        }

        delegate void dgvDelegate(DataTable table);
        private void SetDgvDataSource(DataTable table)
        {
            if (dataGridView1.InvokeRequired)
            {
                Invoke(new dgvDelegate(SetDgvDataSource), new object[] { table });
            }
            else
            {
                dataGridView1.DataSource = table;
            }
        }

        private delegate void pbDelegate(int value);
        private void SetPbValue(int value)
        {
            if (progressBar1.InvokeRequired)
            {
                Invoke(new pbDelegate(SetPbValue), new object[] { value });

            }
            else
            {
                progressBar1.Value = value;
            }
        }

 

以上是关于C# 窗口无假死,进度条的主要内容,如果未能解决你的问题,请参考以下文章

重写C# winform 进度条的样式(要代码示例)

实现winfrom进度条及进度信息提示

C# WinForm自定义进度条

winform 实现单击按钮后显示进度条或等待窗口

C# winform加载子窗体很慢 如何用进度条显示

(68)C#里怎么样提供一个有窗口显示进度条的拷贝目录的功能