×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: C#
Posted by: Mattia Lucariello
Added: Mar 22, 2015 9:51 AM
Views: 38
see for details: http://stackoverflow.com/questions/363377/how-do-i-run-a-simple-bit-of-code-in-a-new-thread
  1. using System.ComponentModel;
  2. ...
  3.     private void button1_Click(object sender, EventArgs e)
  4.     {
  5.         BackgroundWorker bw = new BackgroundWorker();
  6.  
  7.         // this allows our worker to report progress during work
  8.         bw.WorkerReportsProgress = true;
  9.  
  10.         // what to do in the background thread
  11.         bw.DoWork += new DoWorkEventHandler(
  12.         delegate(object o, DoWorkEventArgs args)
  13.         {
  14.             BackgroundWorker b = o as BackgroundWorker;
  15.  
  16.             // do some simple processing for 10 seconds
  17.             for (int i = 1; i <= 10; i++)
  18.             {
  19.                 // report the progress in percent
  20.                 b.ReportProgress(i * 10);
  21.                 Thread.Sleep(1000);
  22.             }
  23.  
  24.         });
  25.  
  26.         // what to do when progress changed (update the progress bar for example)
  27.         bw.ProgressChanged += new ProgressChangedEventHandler(
  28.         delegate(object o, ProgressChangedEventArgs args)
  29.         {
  30.             label1.Text = string.Format("{0}% Completed", args.ProgressPercentage);
  31.         });
  32.  
  33.         // what to do when worker completes its task (notify the user)
  34.         bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
  35.         delegate(object o, RunWorkerCompletedEventArgs args)
  36.         {
  37.             label1.Text = "Finished!";
  38.         });
  39.  
  40.         bw.RunWorkerAsync();
  41.     }