教程集 www.jiaochengji.com
教程集 >  脚本编程  >  Asp.net  >  正文 C# 多线程更新进度条progressBar控件的代码一例

C# 多线程更新进度条progressBar控件的代码一例

发布时间:2016-03-05   编辑:jiaochengji.com
为大家介绍windows应用程序中使用多线程更新控件的方法。以常见的多线程更新进度条为示例。本方法也可解决:“线程间操作无效: 从不是创建控件的线程访问它”的异常。供大家学习参考。

C#进度条的示例代码。

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 temp
{
    delegate void SetValueCallback(int value);
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(Foo));
            t.Start();
        }
        private void Foo()
        {
            for (int i = 1; i <= 100; i++)
            {
                Thread.Sleep(100);
                SetProcessBarValue(i);
                SetLabelValue(i);
            }
        }
        private void SetLabelValue(int value)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.label1.InvokeRequired)
            {
                SetValueCallback d = new SetValueCallback(SetLabelValue);
                this.Invoke(d, new object[] { value });
            }
            else
            {
                this.label1.Text = value.ToString() + '%';
            }
        }
        private void SetProcessBarValue(int value)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.progressBar1.InvokeRequired)
            {
                SetValueCallback d = new SetValueCallback(SetProcessBarValue);
                this.Invoke(d, new object[] { value });
            }
            else
     //http://www.jbxue.com
            {
                this.progressBar1.Value = value;
            }
        }
    }
}

您可能感兴趣的文章:
C# 多线程更新进度条progressBar控件的代码一例
c# 多线程操作progressBar进度条控件的例子
c#进度条如何实现(附简单实例)
jQuery进度条插件 jQuery progressBar
C#进度条ProgressBar和定时器Timer控件的应用举例
c# 进度条 ProgressBar的简单例子
jquery.ui.progressbar 中文文档
c#进度条 progressBar的小例子
使用Android仿微信加载H5页面的进度条
C# 多线程复制文件并显示进度条的代码

关键词: progressBar  多线程  进度条   
[关闭]
~ ~