C# Winform ProgressBar and BackgroundWorker

泪湿孤枕 提交于 2019-11-27 05:24:41

One problem is that you're sleeping for 30 seconds. Normally you'd call ReportProgress at various points within your long-running task. So to demonstrate this, you might want to change your code to sleep for 1 second, but 30 times - calling ReportProgress each time it finishes a sleep.

Another problem is that you're showing your ProgressForm from the background thread. You should start it in the UI thread, but hook the background worker's ProgressChanged event to it. Then when the background worker reports progress, the progress form will be updated.

ReportProgress is the method which you'll have to call in your 'working' method. This method will raise the 'ProgressChanged' event.

In your form, you can attach an eventhandler to the ProgressChanged event. Inside that eventhandler, you can change the position of the progressbar. You can also attach an eventhandler to the RunWorkerCompleted event, and inside that eventhandler, you can close the form which contains the progressbar.

It should be noted you need to set

backgroundWorker1.WorkerReportsProgress = true;

if you want the background worker to raise the ProgressChanged event and

backgroundWorker1.WorkerSupportsCancellation = true;

if you wish to be able to cancel the worker thread.

As the others have said, run the f.ShowDialog() in your UI thread and use ProgressChanged to update the ProgressWindow.

To get the ProgressForm to self close, in backgroundWorker1_RunWorkerCompleted, call f.Close(); This means the long operation has completed and we can close the window.

linnx88

What is needed here is to not pass the entire main form to the class, but simply the instance of your BackgroundWorker! You need to cast the sender as Background worker like so:

private void bgWorker_DoWork(object sender DoWorkEventArgs e)
{
    // Get the BackgroundWorker that raised this event
    BackgroundWorker worker = sender as BackgroundWorker;

    // And now you just send worker to whatever class you need like so:
    bgArgs args = e.Argument as bgArgs;
    MyClass objMyClass = new MyClass();

    MyClass.MyMethod(strValue, args.Option, worker);

    // Do something based on return value.
}

And then in your MyClass.MyMethod() you would do the progress calculations and simply raise the worker.ReportProgress(int percentage) event to update the progress bar or whatnot on your main UI form!

This should work perfectly!

Check out this MSDN article for more details, see their Fibonacci example, it's what they do since CalculateFibonacci is a custom class which sends updates to Main form's UI.

See MSDN BackgroundWorker Class for more details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!