开发者

C# Progressbar won't update with backgroundworker

开发者 https://www.devze.com 2022-12-12 03:14 出处:网络
I am trying to update my progressbar with the backgroundworker. Only this aint working. Here\'s my code:

I am trying to update my progressbar with the backgroundworker. Only this aint working. Here's my code:

private BackgroundWorker _worker;

public Form1(string[] args)
{
    InitializeComponent();

    // Backgroundworker to update the progressbar
    _worker = new BackgroundWorker();
    _worker.WorkerReportsProgress = true;
    _worker.ProgressChanged += worker_ProgressChanged;
    _worker.DoWork += worker_DoWork;
    _worker.RunWorkerCompleted += worker_WorkCompleted;

}

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
    SendItems();
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}
private void worker_WorkCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    _running = false;
    HandleGui();
}

private bool SendItems()
{
    try
    {
        GetEvaluationDocumentsToSend();
        _worker.ReportProgress(16);

        GetModifiedEvaluationDocumentsToSend();
        _worker.ReportProgress(32);

        GetTasksToSend();
        _worker.ReportProgress(48);

        GetPostToSend();
        _worker.ReportProgress(64);

        GetContractDocumentsToSend();
        _worker.ReportProgress(80);

        GetModifiedContractDocumentsToSend();
        _worker.ReportProgress(100);

        return开发者_如何学JAVA true;
    }
    catch (Exception e)
    {
        Log.WriteLog(e.ToString());

        MessageBox.Show(
            "The following error occured while sending the items: \r\n" + e.ToString(),
            "Error",
            MessageBoxButtons.OK,
            MessageBoxIcon.Exclamation);

        return false;
    }
}

private void btnUpdate_Click(object sender, EventArgs e)
{
    _worker.RunWorkerAsync();
}

I don't get any errors, but my progressbar will not update. What am I doing wrong?


Well it works on my machine. What does GetEvaluationDocumentsToSend() do? Perhaps it is taking a lot longer than the other methods so it looks like no progress is made because all of the progress is almost instantaneous? Also, what does HandleGui() do and what is _running used for?


You didn't start the BackgroundWorker !

Add this line after event subscriptions :

_worker.RunWorkerAsync();

EDIT : Now the code shows that you call the RunWorkerAsync()

Try to add Thread.Sleep(1000) after each progress to see if your process is too fast...


try adding a Invoke/BeingInvoke call around your progressbar update:

this.BeginInvoke((MethodInvoker)delegate
{
    progressBar1.Value = e.ProgressPercentage;
});

This is usually the reason UI's are not getting updated.

0

精彩评论

暂无评论...
验证码 换一张
取 消