简体   繁体   English

C#从单独的类更新backgroundworker进度

[英]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... 我没有收到任何错误,backgroundworker正常运行,但是我的文本框从未更新过...

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? 是什么让您说BackgroundWorker运行正常? I see no call to worker.RunWorkerAsync() , and without that it will never start. 我看不到对worker.RunWorkerAsync()调用,没有它,它将永远不会启动。

您不是要启动工作人员!

worker.RunWorkerAsync();

Try This: 尝试这个:

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

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

Hope This help. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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