AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Thursday 17 December 2015

Background worker in c#


Background Worker makes threads easy to implement in Windows Forms applications. Other tasks are running in background worker it will not freeze User Interface. It is required to update the user interface when the task is done.

Let's take an example, I want to bind data in data grid without freezing the User Interface.

Background worker Code
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.RunWorkerAsync();

Create Instance of backgroundworker & create two event handlers "DoWorkEventHandler" & "RunWorkerCompletedEventHandler".

DataTable dt =DataTable();
void worker_DoWork(object sender, DoWorkEventArgs e)
 {    
      dt = GetYourData(); //Fetching Data
 }

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
            grdFeed.DataSource = dt;
}


Here "worker_DoWork" is used for fetching data this method is running in backgroundData without freezing UI. When all data fetches Method "worker_RunWorkerCompleted" is bound data in grid.

0 comments :

Post a Comment

  • Popular Posts
  • Comments