Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How to work with background worker with custom code -Run,Pause,Stop?

I am working with Background Worker but neither i am able to synchronize my progress bar nor able to stop or abort the process.

in my dowork function

void bw_DoWork(object sender, DoWorkEventArgs e)
{
    if(bw.CancellationPending==true)
    {
        e.cancel=true;
        return;
    }
    else
    {
        e.Result = abc();
    }
}
int abc()
{
    //my work
    Count++;
    return count;
}

void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if(bw.CancellationPending==true)
    {
        button17.Visibility = Visibility.Visible;
        label1.Content = "Aborted";
    }
    button17.Visibility = Visibility.Visible;
    label1.Content = "Completed";
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
    if(bw.IsBusy)
    {
        bw.CancelAsync();
    }
}

Now i want to know how could i Synchronize my Progress Bar and how to exit from the process?

like image 304
Neel Bhasin Avatar asked Nov 29 '25 21:11

Neel Bhasin


1 Answers

Have you set the BackgroundWorker.WorkerReportsProgress && BackgroundWorker.WorkerSupportsCancellation properties on your instance to be true?

e.g.

var myBackgroundWorker = new BackgroundWorker();
myBackgroundWorker.WorkerReportsProgress = true;
myBackgroundWorker.WorkerSupportsCancellation = true;
//the rest of the init

If you want to report progress, you need to call the BackgroundWorker.ReportProgress() method from inside your DoWork.

like image 100
Alastair Pitts Avatar answered Dec 02 '25 10:12

Alastair Pitts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!