Search code examples
c#wpfbackgroundworker

C# updating backgroundworker progress from separate class


I am trying to run a function in a different class than the dispatcher through a backgroundworker and have it update the progress on every iteration. I am getting no errors and the backgroundworker is functioning properly, but my textbox never updates...

public partial class MainWindow : Window
{
    public BackgroundWorker worker = new BackgroundWorker();

    public MainWindow()
    {
        InitializeComponent();
        worker.WorkerReportsProgress = true;
        worker.DoWork += new DoWorkEventHandler(workerDoWork);
        worker.ProgressChanged += new ProgressChangedEventHandler(workerProgressChanged);
    }

    private void myButtonClick(object sender, RoutedEventArgs e)
    {
        worker.RunWorkerAsync();
    }

    void workerDoWork(object sender, DoWorkEventArgs e)
    {
        yv_usfm.convert(worker);
    }

    void workerProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        myTextBox.Text = "some text";
    }

}

public class yv_usfm
{
    public static void convert(BackgroundWorker worker)
    {
        int i = 1;
        while (i < 100)
        {
            worker.ReportProgress(i);
            i++;
        }
    }
}

Solution

  • Try This:

    void DoWork(...)
    {
        YourMethod();
    }
    
    void YourMethod()
    {
        if(yourControl.InvokeRequired)
            yourControl.Invoke((Action)(() => YourMethod()));
        else
        {
            //Access controls
        }
    }
    

    Hope This help.