简体   繁体   中英

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++;
        }
    }
}

What makes you say the BackgroundWorker is functioning properly? I see no call to worker.RunWorkerAsync() , and without that it will never start.

您不是要启动工作人员!

worker.RunWorkerAsync();

Try This:

void DoWork(...)
{
    YourMethod();
}

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

Hope This help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM