The easiest way to implement a background worker thread for a form in a Winform application is to use the BackgroundWorker from the System.ComponentModel namespace.
To summarize the changes imagine you have a form were you dropped a button with the default name 'button1'.
- From the toolbox open the component section.
- Select BackgroundWorker and drag it onto the form.
- The default name will be 'backgroundWorker1'.
- Select the backgroundWorker object and inspect its properties.
- Select the Events (it looks like a lightning bolt)
- Doubleclick in the space next to 'DoWork'
- Keep default name: backgroundWorker1_DoWork
- Doubleclick in the space next to 'ProgressChanged'
- Keep default name: backgroundWorker1_ProgressChanged
- Doubleclick in the space next to 'RunWorkerCompleted'
- backgroundWorker1_RunWorkerCompleted
- Button Click Code Handlerprivate void button1_Click(object sender, EventArgs e)
{
this.backgroundWorker1.RunWorkerAsync("From Form");button1.Enabled = false;}
- Background DoWork Handlerprivate void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(1000);string comment = (string) e.Argument;backgroundWorker1.ReportProgress(12, comment + " From Background");Thread.Sleep(10000);}
- ProgressChanged Handler
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
string report = (string)e.UserState;listBox1.Items.Add("From Progress Change Hander");listBox1.Items.Add(report);}
- RunWorkerCompleted Handler
{
button1.Enabled = true;}
Implementation Versions: This code was developed and tested with Visual Studio 2010, C# 4.0 and the .Net Framework 4 Client Profile.
No comments:
Post a Comment