欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

关于C#进度条不能充满100%的解决方案

程序员文章站 2022-05-28 12:57:18
...

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

namespace 进度条显示测试
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

    private void Form1_Load(object sender, EventArgs e)
    {
        progressBar1.Maximum = 7;
        progressBar1.Step =1;
        //Action my = Calculation;
        //this.BeginInvoke(my);
        Thread t = new Thread(Calculation);
        t.IsBackground = true;
        t.Start();

    }

    public void Calculation()
    {
        for (int i = 0; i < 7; i++)
        {
           
            double c = 1 + 3 * 2;
            Thread.Sleep(500);
            ChangeBar();
        }
        Thread.Sleep(600);
        if (this.InvokeRequired)
        {
            Action w = colosbar;
            this.Invoke(w);
        }
        else
        {
            progressBar1.Visible = false; 
        }
       
    }

    public void colosbar()
    {
        progressBar1.Visible = false;
    }

    public void ChangeBar()
    {
        if (this.InvokeRequired)
        {
            Action wt = ChangeBar;
            this.Invoke(wt);
        }
        else
        {
            if (progressBar1.Value < progressBar1.Maximum)
            {
               progressBar1.PerformStep();
                Thread.Sleep(500);
                label1.Text = "已完成" + ((double) progressBar1.Value / progressBar1.Maximum) * 100 + "%";             
               Application.DoEvents();
            }
            
          
         
        }
    }

 
}

}
进度条更新需要一定时间,所以在关闭进度条前需要让程序暂停一下大约600ms,然后在执行关闭操作…