码迷,mamicode.com
首页 > 编程语言 > 详细

【转】ProcessBar的多线程更新

时间:2016-01-19 10:17:59      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

本文转自http://dotnet.chinaitlab.com/CSharp/801729.html

 

在用Windows Form编程时候,我们通常会遇到如此问题:

  1. 后台更新大量处理数据过程。

  2.需要把后台的Log输出到前端,以监控运行状态。

  3. 如果运行大量处理过程,前端会出现白屏状态,这样对用户不友好。

  针对此,我们需求创建多线程来处理后台。用多线程调用处理,按平常处理,是不能更新主线程的控件的,需要做特殊处理。

 

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        delegate void SetValueCallback(int value);

        public Form1()
        {
            InitializeComponent();
        }

        private void btnRun_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.lblStatus.InvokeRequired)
            {
                SetValueCallback d = new SetValueCallback(SetLabelValue);
                this.Invoke(d, new object[] { value });
            }
            else
            {
                this.lblStatus.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.prbStatus.InvokeRequired)
            {
                SetValueCallback d = new SetValueCallback(SetProcessBarValue);
                this.Invoke(d, new object[] { value });
            }
            else
            {
                this.prbStatus.Value = value;
            }
        }
    }
}

 

【转】ProcessBar的多线程更新

标签:

原文地址:http://www.cnblogs.com/CurryZhang/p/5141188.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!