开发者

ReportProgress C# question

I have a background worker thread that contains a loop. For every iteration I would like to update a textbox that shows the user a log of whats going on. For example, if the user was scrapping 200 sites for headlines it would say:

Scraped site1.net Scraped开发者_开发问答 site2.net Scraped site3.net

The only thing I can see that does this is reportProgress, which only excepts an integer. I have no use for reporting the percentage. I would like an event to fire per iteration.

Is this possible?


Use the second overload instead. Set the percentProgress to 0, and set the userState to your string or string[] for the sites.

myBackgroundWorker.ReportProgress(int percentProgress, object userState);

Example:

    private void myBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        // Set your sites dynamically here.

        string[] sites = new string[]
        {
            "Test.com",
            "Example.net",
            "Google.com"
        };

        myBackgroundWorker.ReportProgress(0, sites);
    }

    private void myBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        string[] sites = (string[])e.UserState;

        // Enjoy your string array.
    }


The DoWorkEventArgs class has a property "Argument" of type "object", which can be used to pass anything you want into the background worker.

You could define a thread-safe string property on your view model or other binding source, then pass it in as the argument; then the BackgroundWorker could update it and your UI could be updated through binding or via the WPF Dispatcher, if you are using WPF or silverlight.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜