Search code examples
c#wpfmultithreadingbackgroundworker

Another Background worker


I have looked at msdn and similar questions of stack exchange for how to use background workers.

Basically, my function upload-program does the actual work, but I want a thread to change elements of the ui as it goes (progress bars etc) and as i send events to progress changed. What I've tried is below (harshly edited), it doesn't work and the program seems to cut out after the call to runworkerasync. Is there something simple wrong or was it wrong to send my command "to the other thread"?

BackgroundWorker backgroundUpload = new System.ComponentModel.BackgroundWorker();

The first bit is the call:

        if (backgroundUpload.IsBusy != true)
        {
            backgroundUpload.RunWorkerAsync(work);
                 // a command here for debug purposes (eg a message box) will run
        }
        else
        { //it doesn't go here, this isn't the error}

Then the dowork, it never seems to get here.

    private void backgroundUpload_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        e.Result = UploadProgram((Workload)e.Argument, worker, e); //workload is one of my enums
    }

never seems to get here either.

bool UploadProgram(Workload work, BackgroundWorker worker, DoWorkEventArgs e)
    {
    }

    //also there is progress changed and run worker complete.

Solution

  • In your code is missing the required plumbing to let a BackgroundWorker communicate with the UI

    you need to be sure these properties and events are correctly set

     .....
     backgroundUpload.DoWork += backgroundUpload_DoWork
     backgroundUpload.ProgressChanged += backgroundUpload_ProgressChanged;
     backgroundUpload.WorkerReportsProgress = true;
     .....   
    

    you need an Event handler running on the UI thread that updates your progress bar

    private void backgroundUpload_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar.Value = (e.ProgressPercentage.ToString() + "%");
    }
    

    and while you work to upload file a call to

     worker.ReportProgress(percentComplete);