关于C# WinForm中进度条的实现方法

来源:互联网 发布:刚转行做程序员后悔了 编辑:程序博客网 时间:2024/04/27 14:37


http://www.cnblogs.com/Sue_/articles/2024932.html


进度条是一个软件人性化考虑之一,他给用户的感觉就是程序内部在不停的动作,执行到了什么程度,而不是整个界面僵死,以至于用户不知道程序在做什么!

  看了好几个WinForm程序了,发现他们对进度条的处理完全失去了进度条的作用。他们都是采用Timer来处理,在线程结束的时候,直接赋值进度条达到100%。和我以前做WebForm程序的时候完全不一样,做WebForm程序的时候,进度条是根据总体数据和每步执行后而计算和更新的。在看了这几个WinForm程序后,我在想:是否所有WinForm程序,在进度条的处理上都不能保证实时进度显示?

  其实用Timer来处理,不停的更新进度条只是程序作者偷懒的方法。当然这样的好处就是可以简单化处理进度条,代码量少,不易出错,调试方便。

  还有一种方法,就是可以及时更新进度条的数据的。那就是采用事件驱动机制,在子线程中监视复杂处理过程中的设定的事件,及时更新!直接看代码:
程序代码using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace WindowsApplication1
{
     /// <summary>
     /// Form1 类
     /// </summary>
     public partial class Form1 : Form
     {
         public Form1()
         {
             InitializeComponent();
         }
         private void button1_Click(object sender, EventArgs e)
         {
             //用子线程工作
             new System.Threading.Thread(new System.Threading.ThreadStart(StartDownload)).Start();
         }
         //开始下载
         public void StartDownload()
         {
             Downloader downloader = new Downloader();
             downloader.onDownLoadProgress += new Downloader.dDownloadProgress(downloader_onDownLoadProgress);
             downloader.Start();
         }
         //同步更新UI
         void downloader_onDownLoadProgress(long total, long current)
         {
             if (this.InvokeRequired)
             {
                 this.Invoke(new Downloader.dDownloadProgress(downloader_onDownLoadProgress), new object[] { total, current });
             }
             else
             {
                 this.progressBar1.Maximum = (int)total;
                 this.progressBar1.Value = (int)current;
             }
         }
     }

     /// <summary>
     /// 下载类(您的复杂处理类)
     /// </summary>
     public class Downloader
     {
         //委托
         public delegate void dDownloadProgress(long total,long current);
         //事件
         public event dDownloadProgress onDownLoadProgress;
         //开始模拟工作
         public void Start()
         {
             for (int i = 0; i < 100; i++)
             {
                 if (onDownLoadProgress != null)
                     onDownLoadProgress(100, i);
                 System.Threading.Thread.Sleep(100);
             }
         }
     }
}


0 0
原创粉丝点击