Saturday 11 February 2017

C# Backgroundworker

BackgroundWorker is the class in System.ComponentModel which is used when you need to do some task on the back-end or in different thread while keeping the UI available to users (not freezing the user ) and same time, reporting the progress of the same.
Backgroundworker has three event handlers which basically takes care of everything one needs to make it work.
  1. DoWork – Your actual background work goes in here.
  2. ProgressChanged – When there is a progress in the background work
  3. RunWorkerCompleted – Gets called when background worker has completed the work.
I have created a sample WPF application which demonstrates how to use the background worker in c#.
XAML:
 <ProgressBar x:Name="progressbar" HorizontalAlignment="Left" Height="14" Margin="191,74,0,0" VerticalAlignment="Top" Width="133"/>
 <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="249,97,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
  
On Window initialization, I am creatin a new object of BackgroundWorker and registering the event handlers for the same.
 BackgroundWorker bg;
public MainWindow()
{
InitializeComponent();
bg = new BackgroundWorker();
bg.DoWork += Bg_DoWork;
bg.ProgressChanged += Bg_ProgressChanged;
bg.RunWorkerCompleted += Bg_RunWorkerCompleted;
bg.WorkerReportsProgress = true;

}
Here is the implementation of all three event handlers.
private void Bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Task completed");
}

private void Bg_ProgressChanged(object sender, ProgressChangedEventArgs e)
{

progressbar.Value += 1;
//label.Content = e.ProgressPercentage;
}

private void Bg_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i &lt;= 10; i++)
{
Thread.Sleep(1000); //do some task
bg.ReportProgress(0);
}
}

In order to make this stuff work, you need to trigger the DoWork event and for that , I am using button click event.
progressbar.Value = 0;
progressbar.Maximum = 10;
bg.RunWorkerAsync();

It is very basic example of background worker but it is good to start with.

One must be wondering how it is updating the progress bar if it is working in background.

Well, the ProgressChanged event handler runs on UI thread where as DoWork run on application thread pool. That’s why despite running in the background on different thread, it is not freezing the UI and updating the progressbar upon making progress.
Please leave your comments for any question concerns.

Please note that all my articles and posts are open for suggestion(s) or correction(s).

Creating public class by default Visual Studio


Recently, I came across a silly mistake – where, I was not able to see my newly created class in intellisense in visual studio.

After starting from the scratch, it came to notice that by default visual studio creates class without access specifiers and that is the reason, it became private and it didn't show up in Intellisense.
You can fix it. Here is how. When you try creating new class, it uses the template located under path:

%systemdrive%\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class

You should see the file named class.cs which has content as below.

using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;
$if$ ($targetframeworkversion$ >= 4.5)using System.Threading.Tasks;
$endif$
namespace $rootnamespace$
{
class $safeitemrootname$
{
}
}
Here, change the class definition by adding Public access specifier and save/override the file.
public class $safeitemrootname$

You should be good to go.
Please leave your comments for any question concerns.
Please note that my post is open for suggestion(s) or correction(s).