.

Wednesday, October 8, 2008

C# - Create a thread to run an process or operation in the background.

C# - Create a thread to run an process or operation in the background.

Using threads is an easy way to stop your user interface from freezing up. In C# .Net creating a thread is as easy as draging and dropping. The component to be used is the "BackgroundWorker" that is located in the Components section of your toolbar.
Steps for using threads.

  • Create a new Windows Form Project.
  • Add 2 buttons to your form. One to start the thread and one to stop it.(btnStartThread, btnEndThread).
  • Add a BackgroundWorker component to your form.
Image

  • Create “Click” event handlers for both the buttons. (Go to the properties window, click on the event icon and then dbl-click on the event handlers you want created. ).
Image

  • Create a “DoWork” and “RunWorkerCompleted” event handler for the BackgroundWorker.
Image

  • Change the BackgroundWorker’s WorkerSupportCancellation property to true. This will enable the cancellation of a running thread.
  • Add “using System.Threading;” To the using part of your program. This will be used to create sleep event.
Next add the following example code to the event handlers you just created.


Code for the "Start Thread" button.

private void btnStartThread_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}


Code for the "End Thread" button.

private void btnEndThread_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}


Code for the Process you want to run.

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Make the thread result false by default.
e.Result = false;

// listen for when the cancel button is pressed...
while (!backgroundWorker1.CancellationPending)
{
//-- Background Code Begin -----------------------------------
// This is the process that you want to run. My Example will
// wait for 3 seconds.
//------------------------------------------------------------

for (int k = 1; k < 3000; k++)
{
Thread.Sleep(1);
// Test if the thread was canceled.
if (backgroundWorker1.CancellationPending) break;
}

//-- Background Code Ends- -----------------------------------

// This is a result indicator that shows the background
// process has finished successful.
e.Result = true;

// Run the loop once and exit
break;
}


if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
// Do a roll back if you need to.
}
}


Result of the process that was run.

private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
// The user canceled the operation.
MessageBox.Show("The operation was canceled");
}
else if (e.Error != null)
{
// There was an error during the operation.
string msg = String.Format("An error occurred: {0}", e.Error.Message);
MessageBox.Show(msg);
}
else if ((bool)e.Result)
{
// The operation completed normally.
string msg = String.Format("Process was completed successful ");
MessageBox.Show(msg);
}

}

No comments:

.