C# updating backgroundworker progress from separate class

早过忘川 提交于 2019-12-11 11:05:35

问题


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

回答1:


Try This:

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

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

Hope This help.




回答2:


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




回答3:


You're not starting the worker!

worker.RunWorkerAsync();


来源:https://stackoverflow.com/questions/15707156/c-sharp-updating-backgroundworker-progress-from-separate-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!