C#Winform进度栏在do_work事件中的操作期间不会更新

时间:2018-12-19 08:40:39

标签: c# winforms progress

我有一个简单的获胜表格应用程序,我想在此过程中显示进度栏 在网格视图中从数据库加载数据。在我的项目进度栏中,完成进度完成后或根本不显示进度。这是我的代码。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    ADTNEWEntities db = new ADTNEWEntities();
    private delegate void MyDeligate();
    private void myFunction()
    {
        dataGridView1.DataSource = db.CashPays.ToList();
    }
    private void backgroundWorker1_DoWork(object sender,DoWorkEventArgs e)
    {
        this.Invoke(new updateProgressDelegate(updateProgressBar));
        //call your code here
        Invoke(new MyDeligate(myFunction));
    }
       private void backgroundWorker1_RunWorkerCompleted(object sender,        RunWorkerCompletedEventArgs e)
    {
        progressBar1.Visible = false;
    }
 private void button1_Click(object sender, EventArgs e)
    {
        if (!backgroundWorker.IsBusy)
            backgroundWorker.RunWorkerAsync();
    }
    BackgroundWorker backgroundWorker;
    private void Form1_Load(object sender, EventArgs e)
    {
        backgroundWorker = new BackgroundWorker();
        progressBar1.Visible = false;
        progressBar1.Style = ProgressBarStyle.Marquee;
        backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
  }
    private delegate void updateProgressDelegate();

    private void updateProgressBar()
    {
        progressBar1.Visible = true;
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Update();
    }
}

1 个答案:

答案 0 :(得分:0)

您应将该代码的 all 替换为:

private async void button1_Click(object sender, EventArgs e)
{
    progressBar1.Visible=false;
    var data=await db.CashPays.ToListAsync();
    dataGridView1.DataSource = data;
    progressBar1.Visible=true;
}

private void Form1_Load(object sender, EventArgs e)
{
    progressBar1.Visible = false;
    progressBar1.Style = ProgressBarStyle.Marquee;
}

当必须执行的工作必须在UI上运行时,使用(现在已过时的)BGW或Task.Run没有意义。设置DataSource是一项UI操作。虽然可以使用ToListAsync()ToArrayAsync()

在后台执行数据加载

ToListAsync()不提供任何进度事件,因此进度条应使用Marquee风格