TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Fun with the BackgroundWorker Class

Another nice helper class in the .NET 2.0 Framework is the BackgroundWorker class. As a disclaimer, the following is a simplistic, lame example, but it gives the the basic idea behind its pattern of use. A far better use is using WinForms with perhaps a progress bar control. Another thing you can do is store state. Mike Woodring has a very interesting post about this class as well - be sure to check it out.

class Program

{

    static System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();

    static void Main(string[] args)

    {

       

        worker.DoWork += new System.ComponentModel.DoWorkEventHandler(SomeLongRunningTask);

        worker.WorkerReportsProgress = true;

        worker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(worker_ProgressChanged);

        worker.RunWorkerAsync();

        Console.ReadKey();

    }

 

    static void worker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)

    {

        Console.WriteLine(e.ProgressPercentage);

    }

 

    static void SomeLongRunningTask(object sender, System.ComponentModel.DoWorkEventArgs e)

    {

        //simulate work

        for (int i = 1; i <= 10; i++)

        {

            worker.ReportProgress(i * 10);

            Thread.Sleep(500);

        }

    }

}


Digg!

posted on Saturday, November 05, 2005 10:56 PM

Feedback

No comments posted yet.