midrange.com code scratchpad
Name:
Threading
Scriptlanguage:
C#
Tabwidth:
2
Date:
10/31/2008 02:13:41 pm
IP:
Logged
Description:
The user was to lazy to give a description
Code:
  1. using System;
  2. using System.Windows.Forms;
  3. using System.Threading;
  4.  
  5. namespace WinForm1
  6. {
  7.   public partial class Form1 : Form
  8.   {
  9.     public Form1()
  10.     {
  11.       InitializeComponent();
  12.     }
  13.  
  14.     private void button1_Click(object sender, EventArgs e)
  15.     {
  16.       ParameterizedThreadStart pts = new ParameterizedThreadStart(Background.DoLongProcess);
  17.       Thread getDataThread = new Thread(pts);
  18.       getDataThread.Name = "DataQGet";
  19.       
  20.       //Go below normal, not time critical.
  21.       getDataThread.Priority = ThreadPriority.BelowNormal;
  22.       
  23.       //Auto-kill thread when foreground threads die
  24.       getDataThread.IsBackground = true;
  25.       
  26.       //Will use COM, go STA!
  27.       getDataThread.SetApartmentState(ApartmentState.STA);
  28.       
  29.       //And we're off...
  30.       getDataThread.Start(this);
  31.     }
  32.  
  33.     public void GotData(string TheData)
  34.     {
  35.       //We add to listbox here. Do what you will. 
  36.       //Remember, you're now on the UI thread!
  37.       listBox1.Items.Add(TheData);
  38.     }
  39.   }
  40.  
  41.   class Background
  42.   {
  43.     static public void DoLongProcess(object StateInfo)
  44.     {
  45.       Form1 theForm = (Form1)StateInfo;
  46.  
  47.       //Repeat forever
  48.       while (true)
  49.       {
  50.         //This is the 'long process'
  51.         System.Threading.Thread.Sleep(5000);
  52.         string theData = DateTime.Now.ToString();
  53.  
  54.         //Update the form w/the data from the long process
  55.         //Remember, to update the UI from another thread we must invoke() the update
  56.         if (theForm.InvokeRequired)
  57.           theForm.Invoke((MethodInvoker)delegate { theForm.GotData("Invoked: " + theData); });
  58.         else
  59.           theForm.GotData(theData);
  60.       }
  61.     }
  62.   }
  63. }
  64.  
© 2004-2019 by midrange.com generated in 0.009s valid xhtml & css