user2952817 user2952817 - 1 year ago 238
C# Question

Running a BackgroundWorker continuously

I need to be able to continuously run my

. The
event contains a pool threaded process and the
updates my UI.

I have not been able to find a way to infinitely loop the
method without the whole program freezing. Any help would be greatly appreciated.

Answer Source

You have to make a loop in your DoWork-Method. To update your UI you shoud use the ProgressChanged-Method. Here is a small example how this can look like

 public Test()
        BackgroundWorker backgroundWorker = new BackgroundWorker
                 WorkerReportsProgress = true,
                WorkerSupportsCancellation = true
        backgroundWorker.DoWork += BackgroundWorkerOnDoWork;
        backgroundWorker.ProgressChanged += BackgroundWorkerOnProgressChanged;

    private void BackgroundWorkerOnProgressChanged(object sender, ProgressChangedEventArgs e)
        object userObject = e.UserState;
        int percentage = e.ProgressPercentage;

    private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs e)
        BackgroundWorker worker = (BackgroundWorker) sender;
        while (!worker.CancellationPending)
            //Do your stuff here
            worker.ReportProgress(0, "AN OBJECT TO PASS TO THE UI-THREAD");