C# backgroundWorker reports string?

可紊 提交于 2019-11-30 23:44:40

问题


How can I report a string (like "now searching file. . .", "found selection. . .") back to my windows.form from a backgroundWorker as well as a percentage. Additionally, I have a large class that contains the method I want to run in the backgroundWorker_Work. I can call it by Class_method(); but i am then unable to report my percentage done or anything from the called class, only from the backgroundWorker_Work method.

Thanks!


回答1:


I'm assuming WCF also have the method

public void ReportProgress(int percentProgress, Object userState); 

So just use the userState to report the string.

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
 //report some progress
 e.ReportProgress(0,"Initiating countdown");

// initate the countdown.
}

And you'll get that "Initiating countdown" string back in ProgressChanged event

private void worker_ProgressChanged(object sender,ProgressChangedEventArgs e) 
{
  statusLabel.Text = e.UserState as String;
}



回答2:


You can use the userState parameter of ReportProgress method to report that strings.

Here's an example from MSDN:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    // This method will run on a thread other than the UI thread.
    // Be sure not to manipulate any Windows Forms controls created
    // on the UI thread from this method.
    backgroundWorker.ReportProgress(0, "Working...");
    Decimal lastlast = 0;
    Decimal last = 1;
    Decimal current;
    if (requestedCount >= 1)
    { AppendNumber(0); }
    if (requestedCount >= 2)
    { AppendNumber(1); }
    for (int i = 2; i < requestedCount; ++i)
    {
        // Calculate the number.
        checked { current = lastlast + last; }
        // Introduce some delay to simulate a more complicated calculation.
        System.Threading.Thread.Sleep(100);
        AppendNumber(current);
        backgroundWorker.ReportProgress((100 * i) / requestedCount, "Working...");
        // Get ready for the next iteration.
        lastlast = last;
        last = current;
    }

    backgroundWorker.ReportProgress(100, "Complete!");
}



回答3:


Read Simple Multi-threading in Windows Forms.

It's a 3-part series.




回答4:


use a delegate.



来源:https://stackoverflow.com/questions/1289310/c-sharp-backgroundworker-reports-string

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