Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » WPF » Multithreading in WPF: Part II

Multithreading in WPF: Part II

In this article we will consider the safest approach to run background task in WPF.

Author Rank :
Page Views : 6156
Downloads : 179
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
BackgroundWorker.zip
 
 
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


The BackgroundWorker

We had seen in the previous part that one way to perform asynchronous operation was using the thread class.We create an object of thread class and after supplying it with the method name which contains our asynchronous code we call the thread.start() method. This approach is usefull because we have complete control over the thread object.We can control the threads priority,status(like abort,resume).

However this approach has a drawback since if we access shared data we need to use locking.

In this article we will consider the safest approach to run background task :

The System.ComponentModel.BackgroundWorker class.

We can pass an object to BackgroundWorker.RunWorkerAsync() method which we can access in the DoWork method When the BackgroundWorker begins executing, it grabs a free thread from the CLR thread pool and then fires the DoWork event from this thread. DoWork method contains the logic to perform a time consuming task.

Once the work is complete, the BackgroundWorker fires the RunWorkerCompleted event to notify our application that the work is completed. Here we can access shared data and our user interface, without incurring any problems.

We can not access shared data (such as fields in our window class) or user interface objects in the DoWork eventHandler.In the DoWork eventhandler DoWorkEventArgs object is used for retrieving and returning information. DoWorkEventArgs.Argument is used for accesing the input parameters and DoWorkEventArgs.Result is used for passing the result to the RunWorkerCompleted eventhandler.

In the following example we call the backgroundWorker.RunWorkerAsync method from the button click eventhandler.We declare the backgroundworker variable as a class level variable and retrieve it from the resources collection which we added in the xaml.

    <Window.Resources>
        <cm:BackgroundWorker x:Key="backgroundWorker"
WorkerReportsProgress="True" WorkerSupportsCancellation="True"
DoWork="backgroundWorker_DoWork"
ProgressChanged="backgroundWorker_ProgressChanged"
RunWorkerCompleted="backgroundWorker_RunWorkerCompleted">
        </cm:BackgroundWorker>
    </Window.Resources>

BackgroundWorker.RunWorkerAsync calls the Dowork method in which we retrieve the input.

parameters and after performing the operations sets the "result" property of the DoWorkEventArgs argument which we access in the RunWorkerCompleted eventhandler to retrieve the result.

From the search button click we are calling the backgroundWorker.RunWorkerAsync()method.From the DowWork method we are calling the ProcessTask method in which we simulate a long running task by calling the thread.Sleep .

Supporting Cancellation and Progress

It's just as easy to add support for canceling a long-running task with the BackgroundWorker. The first
step is to set the BackgroundWorker.WorkerSupportsCancellation property to true.

To request a cancellation, your code needs to call the BackgroundWorker.CancelAsync() method. In
this example, the cancellation is requested when a Cancel button is clicked.Here is the code that performs cancelaltion of the task.

   private void btnCancel_Click(object sender, RoutedEventArgs e)
   {
       backgroundWorker.CancelAsync();
   }


The above code itself is not sufficient.

  1. The code that's performing the task needs to explicitly check for the cancel request, perform any required cleanup, and return.
     
  2. The code in our DoWork event handler also needs to explicitly set the DoWorkEventArgs.Cancel property to true to complete the cancellation.

The BackgroundWorker also provides built-in support for tracking progress, which is useful for keeping

the client informed about how much work has been completed in a long-running task.

Following needs to be done for updating the progress of the task.

  1. The DoWork event handling code or the method that implements the logic for our long running task needs to call the BackgroundWorker.ReportProgress() method and provide an estimated percent complete
  2.   
  3. Every time you call ReportProgress(), the BackgroundWorker fires the ProgressChanged event. You can react to this event to read the new progress percentage and update the user interface.

We can update the progress bar by using the following code:

progress.Value = e.ProgressPercentage;

If we execute the attached code we will get the following screen.

MWPF1.gif

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Ashish Shukla
Having more than 7 years of experience in .NET,C#,Silverlight and SQL Server.Like to read books and travel in spare time.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Thanks for your posting by Brian On May 31, 2010
Imagine that the ProcessTask method in your example creates a new object A and object A creates a new object B. How is it possible for both object A and object B to report back to mainwindows and update the progressbar? Sorry if this is simple, but for me it's not :-)
Reply | Email | Modify 
Windows Forms by Sam On August 4, 2011
Is the BackgroundWorker class the same in WPF as it is in Windows Forms? If it is then it will be useful for those of us familiar with it in Windows Forms that it is the same for WPF.
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.