CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    May 2011
    Posts
    4

    Using a Background Worker with a class

    I haven't used a background worker before; all of the examples I've seen involve a single form. Can I use a background worker with an external class? (where the crunching is happening)
    i.e.: I have a form that calls a routine in a class, and I would like to display a progress bar on the form with the progress of that routine. If anyone has a code sample that would be great.

  2. #2
    Join Date
    Jan 2007
    Posts
    491

    Re: Using a Background Worker with a class

    Of course you can... just call the routine of the external class from within the BackgroundWorker's DoWork event.

  3. #3
    Join Date
    May 2011
    Posts
    4

    Re: Using a Background Worker with a class

    Thanks for the reply. If I call the external routine from the main form in the DoWork routine, how do I use ReportProgress to get it's status?
    For example, if the code is like this, how do I find out the progress of the DoSomeWork routine?

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
    Dosomeworkclass dosomeworkclass = new Dosomeworkclass();
    dosomeworkclass.Dosomework();
    }

    The examples I've seen have code like:
    backgroundWorker1.ReportProgress(i, DateTime.Now);
    but that code is in the form and not an external class.

  4. #4
    Join Date
    Jan 2007
    Posts
    491

    Re: Using a Background Worker with a class

    There's no magic - the computer can't guess how much time your method will take to run. You need to report as-you-go from within the external method.
    For example, if there's a for loop of 10 iterations in your method, you should probably call ReportProgress with the value i*10 in the i-th iteration.
    Pass the BackgroundWorker as a constructor argument to "Dosomeworkclass", and call its ReportProgress method inside the "Dosomework" method in some way that makes sense.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured