BackgroundWorker simple test

So. I wanted to try the BackgroundWorker since it’s been several years since I used it.

I also happened to be a good project for a first simple blog post. If I ever churn out a third post, remains to be seen.

As for the code, it is as simple as it can be. But if anyone can benefit anything from seeing this, it’s all good.

public partial class MainWindow : Window
    {
        private BackgroundWorker worker;

        public MainWindow()
        {
            InitializeComponent();

            worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler(OnWorkerDoWork);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnWorkerCompleted);
            worker.ProgressChanged += new ProgressChangedEventHandler(OnWorkerProgressChanged);
            worker.WorkerReportsProgress = true;
            progressBar.Minimum = 0;
            progressBar.Maximum = int.MaxValue;
        }

        private void OnWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            textBlock.Text = "Complete";
        }

        private void OnButtonClick(object sender, RoutedEventArgs e)
        {
            if (!worker.IsBusy)
            {
                worker.RunWorkerAsync();
            }
        }

        private void OnWorkerProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            textBlock.Text = e.ProgressPercentage.ToString();
            progressBar.Value = e.ProgressPercentage;
        }

        private void OnWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            int check = int.MaxValue / 100;
            for (int i = 1; i < int.MaxValue; i++)
            {
                if (i % check == 0)
                {
                    worker.ReportProgress(i);
                }
            }
        }
    }

And the XAML:

<Window 
    x:Class="BackgroundWorkerTest.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" 
    Height="350" Width="525">
    <StackPanel>
        <TextBlock 
            x:Name="textBlock" 
            Text="" 
            HorizontalAlignment="Center" 
            VerticalAlignment="Center" 
            FontSize="20" 
            FontWeight="Bold"/>
        <Button 
            Content="Start" 
            Height="23" 
            Name="startButton" 
            Width="75" 
            Click="OnButtonClick"/>
        <ProgressBar 
            x:Name="progressBar" 
            Height="30"/>
    </StackPanel>
</Window>

Leave a Reply

You must be logged in to post a comment.