05 September 2012

Backgroundworker in C#.Net

                Today, Develpers use threading in their Project. So Today, I will explaining threading and threading Concepts.I am using Backgroundworker and Timer.
1.    It is a light weight Component.
2.    It makes threads easy to implement in Windows Form.
3.    UI doesn’t freeze .Because Intensive task needs to be done on another Thread.
Three Threads in Dot Net:
1.    Thread
2.    ThreadPool
3.    Backgroundworker
We will discuss about first 2 in later Articles.Now we discuss about Backgroundworker.
Three Events in Backgroundworker:
1)    Dowork Event.
2)    ProgressChanged Event.
3)    RunWorkerCompleted Event.
1)   Dowork Event:
                         First, Dowork event will start.
                          User can give a expensive code in this Event.
2)   ProgressChanged Event:
add code to indicate the progress, such as updating the user interface.
3)   RunWorkerCompleted Event:
     It is raised when the background worker has completed.
How to Start Backgroundworker?     
  Using backgroundworker1.RunWorkAsync();
How to Stop Backgroundworker?     
  Using backgroundworker1. CancelAsync ();
Where to set RunWorkAsync() and CancelAsync ()?
  You can set where ever you want .
For Eg:
    We have Two Button. One is Start Thread and another One is Stop Thread.
·         Call RunWorkAsync() in Start Thread Button.
·         Call CancelAsync ()  in Stop Thread Button.
I think, you get idea about Background worker and Thread.Now we will go to our Project.This is a Simple Project.
Project Name: File(s)TransferSystem(FTS).
Project Description: Copy file(s) One location to another location.
This following message will show when user doesn’t true workerSupportsCancellation.

  User will declare a namespace for Directory,that is called “System.IO”.
  User will declare for SorucePath and Designation path using string Data Type.
  Use Backgroundworkernad One button in the Project
  Create a Two Method for create Directory and Copy file(s) from One Directory to another Directory.
Method Name:CreateDirectory and assign a Parameter.
Method Desc:Create Directory in the User Specified .Method also check whether Directory exists.
Method Name: fileCopy and assign two Parameter.
Method Desc: file(s) Copy from One locaiton to another location.
Backgroundworker_Dowork Event:call fileCopy method.
Backgroundworker_RunWorkerCompleted Event: To cancel backgrounderworker using Backgroundworker1.CancelAsync() method.
Button1_Click Event:Call Backgroundworker1.RunWorkerAsync() method.
How it will Work?
    Backgroundworker will start when User Press “Button1”.
   After file(s) Transfer Backgroundworker will stop.
    Before run application.Please follow this step.
    Go To Backgroundworker Propoerty
    Change WorkerSupportsCancellation false to true.
  Thanks for reading this Article.I hope , It will help you.Please send your comments and Feedback.

No comments: