Sunday, May 24, 2009

Working with Background Worker in Silverlight 2.0.

 

In this lab, we we try to work with Background worker class which plays a very important role for Silverlight application-

Background Worker class-: Any time consuming operation when you run on your User Interface, it makes your user interface non-responsive. For example, database transactions like bulk upload or insert Or any download from server side. In such cases if you want your User Interface Responsive along with long running process, BackgroundWorker class will be very much helpful.

So let’s start by

1) creating a new Silverlight application with the name “SLBackgroundWorker” by using Visual studio 2008.

2) Once you create the project, let’s open the same project by using Microsoft Expression Blend and start designing digital watch as shown bellow-

DigitalWatchDesign

3) Once you finish the design, Expression Blend will generate the code as shown bellow-

<UserControl x:Class="SLBackgroundWorkerApplication.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Width="400" Height="300">
<Canvas x:Name="LayoutRoot" Background="Black">
<Button Content="Start Clock !!" x:Name="btnStartColoring" Height="50"
Width="100" Canvas.Top="220" Canvas.Left="89" Click="btnStartColoring_Click"/>
<Button Content="Stop Clock!!" x:Name="btnStopColoring" Height="50"
Width="100" Canvas.Top="220" Canvas.Left="209" Click="btnStopColoring_Click"/>
<Border Height="63" Width="384" Canvas.Left="8" Canvas.Top="18"
BorderThickness="10,10,10,10">
<Border.BorderBrush>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF595854"/>
<GradientStop Color="#FFDEC62A" Offset="1"/>
</LinearGradientBrush>
</Border.BorderBrush>
</Border>
<TextBlock Height="56" Width="108.969" Canvas.Left="19" Canvas.Top="16"
Text="00H" TextWrapping="Wrap" Foreground="#FFFFFFFF" FontSize="48"
HorizontalAlignment="Center" VerticalAlignment="Top" x:Name="txtHrs"/>
<TextBlock Height="56" Width="101.938" Canvas.Left="127" Canvas.Top="16"
Text="00M" TextWrapping="Wrap" Foreground="#FFFFFFFF" FontSize="48"
HorizontalAlignment="Center" VerticalAlignment="Top" x:Name="txtMins"/>
<TextBlock Height="56" Width="105" Canvas.Left="237" Canvas.Top="16"
Text="00S" TextWrapping="Wrap" Foreground="#FFFFFFFF" FontSize="48"
HorizontalAlignment="Center" VerticalAlignment="Top" x:Name="txtSecs"/>
</Canvas>
</UserControl>





3) Now open the same project by Visual studio 2008 and write button click event for both of our buttons “Start Clock!!” and “Stop Clock!!”.



4) Now switch back to Page.xaml.cs file and import the namespace as shown bellow-




using System.ComponentModel;
using System.Threading;





5) Now write bellow code in Page.xaml.cs on “Start Clock!!” Button click event as shown bellow-




BackgroundWorker bgWorker;
private void btnStartColoring_Click(object sender, RoutedEventArgs e)
{
bgWorker = new BackgroundWorker();
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.ProgressChanged += new ProgressChangedEventHandler
(bgWorker_ProgressChanged);
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler
(bgWorker_RunWorkerCompleted);
bgWorker.RunWorkerAsync();
bgWorker.WorkerReportsProgress = true;
bgWorker.WorkerSupportsCancellation = true;
}






Background worker class will provide couple of methods, events and properties-



i) DoWork Event-: This event will get fired as soon as you give a call to RunWorkerAsync() method. This event will give a call to a method where you can start you time consuming work.



ii) When you start your work, it is a good practice to check whether the work which you have started is cancelled or not. To Support asynchronous cancellation, you will have to make WorkerSupportsCancellation property to True.



iii) ProgressChanges event will let you know the progress updates. For that you must set property called WorkerReportsProgress to True. It will get fired when you give a call to method “”.



6) Let’s write a code for DoWork Method as shown bellow-




void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
int value = 0;
while ((value < 60) && (!bgWorker.CancellationPending))
{
Thread.Sleep(1000);
value++;
bgWorker.ReportProgress(value);
}
if (bgWorker.CancellationPending)
{
e.Cancel = true;
}
if (value == 60)
{
value = 0;
bgWorker_DoWork(sender, e);
}





7) Now, let’s declare few variables to show Seconds, Minutes and Hours as shown bellow and write a code for ProgressChanged Method-



static int min = 0;
static int hr = 0;
static int sec = 0;
void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
sec = e.ProgressPercentage;
if (sec <= 9)
{
txtSecs.Text = "0" + e.ProgressPercentage.ToString() +"S";
}
else
{
txtSecs.Text = e.ProgressPercentage.ToString() + "S";
}

if (e.ProgressPercentage == 60)
{
min++;
if (min <= 9)
{
txtMins.Text ="0"+ min.ToString() + "M";
}
else
{
txtMins.Text = min.ToString() + "M";
}
sec = 0;
}
if (min == 60)
{
hr++;
if (min <= 9)
{
txtMins.Text = "0" + min.ToString() + "H";
}
else
{
txtMins.Text = min.ToString() + "H";
}
min = 0;
}
}





8) Now the last step, let’s write a code to cancel the Background worker thread on “Stop Clock!!” button click event as shown bellow-



private void btnStopColoring_Click
(object sender, RoutedEventArgs e)
{
bgWorker.CancelAsync();
}





9) That’s All !! Hit F5 and see your Digital clock you can start as well as Stop as per your requirement !!







Now as you have completed writing the fourteenth Silverlight Lab, let’s have a closer look on fifteenth lab “Working with File Dialog box in Silverlight 2.0.

1 comment: