Advertisement
digemall

BackGroundWorker usage example

Jan 23rd, 2013
3,936
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.51 KB | None | 0 0
  1. // This is an example of BackGroundWorker usage.
  2. // To test it, create a Windows Forms Application project, and replace the code in Form1.cs with the following.
  3. // Once you run the application, click the button and the 2 datagridviews will be filled from the worker thread.
  4.  
  5. using System;
  6. using System.ComponentModel;
  7. using System.Data;
  8. using System.Windows.Forms;
  9. using System.Threading;
  10.  
  11. namespace Forms
  12. {
  13.     public partial class Form1 : Form
  14.     {
  15.         #region Helper classes
  16.  
  17.         class NewDataSource
  18.         {
  19.             public int Grid { get; set; } // is the data source for grid 1 or 2
  20.             public DataTable DataSource { get; set; }
  21.         }
  22.         class NewLabel
  23.         {
  24.             public int Label { get; set; } // is the text for label 1 or 2
  25.             public string Text { get; set; }
  26.         }
  27.  
  28.         #endregion
  29.  
  30.         #region Fields
  31.  
  32.         SplitContainer splitContainer;
  33.         DataGridView dataGridView1;
  34.         DataGridView dataGridView2;
  35.         TextBox textBox1;
  36.         TextBox textBox2;
  37.         Button button;
  38.  
  39.         BackgroundWorker bkgWorker;
  40.  
  41.         static Random rand = new Random(123);
  42.  
  43.         #endregion
  44.  
  45.         #region CTOR
  46.  
  47.         public Form1()
  48.         {
  49.             InitializeComponent();
  50.             this.InitControls();
  51.             this.InitBackGroundWorker();
  52.         }
  53.  
  54.         #endregion
  55.  
  56.         #region Initializations
  57.  
  58.         private void InitControls()
  59.         {
  60.             this.textBox1 = new TextBox();
  61.             this.textBox1.Dock = DockStyle.Top;
  62.             this.textBox1.ReadOnly = true;
  63.             this.textBox1.Text = " ---- empty ---- ";
  64.             this.textBox2 = new TextBox();
  65.             this.textBox2.Dock = DockStyle.Top;
  66.             this.textBox2.ReadOnly = true;
  67.             this.textBox2.Text = " ---- empty ---- ";
  68.             this.dataGridView1 = new DataGridView();
  69.             this.dataGridView1.Dock = DockStyle.Fill;
  70.             this.dataGridView2 = new DataGridView();
  71.             this.dataGridView2.Dock = DockStyle.Fill;
  72.  
  73.             this.splitContainer = new SplitContainer();
  74.             this.splitContainer.Dock = DockStyle.Fill;
  75.            
  76.             this.splitContainer.Panel1.Controls.Add(this.textBox1);
  77.             this.splitContainer.Panel1.Controls.Add(this.dataGridView1);
  78.  
  79.             this.splitContainer.Panel2.Controls.Add(this.textBox2);
  80.             this.splitContainer.Panel2.Controls.Add(this.dataGridView2);
  81.  
  82.             this.button = new Button();
  83.             this.button.Dock = DockStyle.Bottom;
  84.             this.button.Text = "Start Elaboration";
  85.             this.button.Click += new EventHandler(button_Click);
  86.  
  87.             this.Controls.Add(this.splitContainer);
  88.             this.Controls.Add(this.button);
  89.  
  90.             this.splitContainer.SplitterDistance = (this.splitContainer.Width - this.splitContainer.SplitterWidth) / 2;
  91.         }
  92.  
  93.         private void InitBackGroundWorker()
  94.         {
  95.             this.bkgWorker = new BackgroundWorker();
  96.             this.bkgWorker.WorkerReportsProgress = true;
  97.             this.bkgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
  98.             this.bkgWorker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
  99.             this.bkgWorker.DoWork += new DoWorkEventHandler(worker_DoWork);
  100.         }
  101.  
  102.         #endregion
  103.  
  104.         #region Event Handlers
  105.  
  106.         void button_Click(object sender, EventArgs e)
  107.         {
  108.             this.button.Enabled = false; // disable the button to avoid multiple elaborations
  109.  
  110.             this.bkgWorker.RunWorkerAsync();
  111.         }
  112.  
  113.         void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
  114.         {
  115.             if (e.UserState is NewLabel)
  116.             {
  117.                 var newLabel = (NewLabel)e.UserState;
  118.                 if (newLabel.Label == 0)
  119.                     this.textBox1.Text = newLabel.Text;
  120.                 else if (newLabel.Label == 1)
  121.                     this.textBox2.Text = newLabel.Text;
  122.             }
  123.             else if (e.UserState is NewDataSource)
  124.             {
  125.                 var newDataSource = (NewDataSource)e.UserState;
  126.                 if (newDataSource.Grid == 0)
  127.                     this.dataGridView1.DataSource = newDataSource.DataSource;
  128.                 else if (newDataSource.Grid == 1)
  129.                     this.dataGridView2.DataSource = newDataSource.DataSource;
  130.             }
  131.         }
  132.  
  133.         void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  134.         {
  135.             this.button.Enabled = true; // enable the button again
  136.         }
  137.  
  138.         void worker_DoWork(object sender, DoWorkEventArgs e)
  139.         {
  140.             // we're on another thread (not the UI thread)
  141.             // so we can perform the elaboration here
  142.             var worker = (BackgroundWorker)sender;
  143.            
  144.             // get data for GRID and LABEL 1
  145.             var data1 = GetDataFromDB();
  146.             worker.ReportProgress(0, new NewLabel() { Label = 0, Text = "Grid has: " + data1.Rows.Count + " rows" });
  147.             Thread.Sleep(1000); // simulate another delay of 1 sec
  148.             worker.ReportProgress(0, new NewDataSource() { Grid = 0, DataSource = data1 });
  149.  
  150.  
  151.             // get data for GRID and LABEL 2
  152.             var data2 = GetDataFromDB();
  153.             worker.ReportProgress(0, new NewLabel() { Label = 1, Text = "Grid has: " + data2.Rows.Count + " rows" });
  154.             Thread.Sleep(1000); // simulate another delay of 1 sec
  155.             worker.ReportProgress(0, new NewDataSource() { Grid = 1, DataSource = data2 });
  156.  
  157.             // N.B. here we're updating the datagridview whenever we get the data.
  158.             // another approach could be collecting all the datasources and set them to e.Result = datasources
  159.             // then update the datagridviews after the finish of the elaboration in RunWorkerCompleted event handler
  160.         }
  161.  
  162.         #endregion
  163.  
  164.         #region Elaboration Methods
  165.  
  166.         private DataTable GetDataFromDB()
  167.         {
  168.             var dt = new DataTable();
  169.             dt.Columns.Add("ID", typeof(int));
  170.             dt.Columns.Add("Name", typeof(string));
  171.             int nRows = rand.Next(20, 300);
  172.             for (int i = 0; i < nRows; i++)
  173.             {
  174.                 int id = rand.Next(1, 100000);
  175.                 dt.Rows.Add(id, "Name of id: " + id);
  176.             }
  177.             Thread.Sleep(2000); // to simulate DB delay (2 seconds)
  178.             return dt;
  179.         }
  180.  
  181.         #endregion
  182.     }
  183. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement