Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 7th, 2012  |  syntax: None  |  size: 1.24 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Delegates in Threads and Annonymous methods - Update controls in new Thread
  2. public partial class DynamicType : Form
  3.     {
  4.         delegate void Del(String x);
  5.  
  6.         public DynamicType()
  7.         {
  8.             InitializeComponent();
  9.         }
  10.  
  11.         private void DynamicType_Load(object sender, EventArgs e)
  12.         {
  13.             System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(StartThread));
  14.             t.Start();
  15.         }
  16.  
  17.         private void StartThread()
  18.         {
  19.             this.Invoke(new Del(UpdateLabel), new object[] { "Hi" });
  20.         }
  21.  
  22.         private void UpdateLabel(String str)
  23.         {
  24.             label1.Text = str;
  25.         }
  26.     }
  27.        
  28. private void StartThread()
  29.         {
  30.             UpdateLabel("Hi");
  31.         }
  32.  
  33.  
  34.  
  35. private void UpdateLabel(String str)
  36.         {
  37.             Del Label = delegate(String k)
  38.              {
  39.                  label1.Text = k;
  40.  
  41.              };
  42.             Label("hi");
  43.         }
  44.        
  45. this.Invoke(new Del(UpdateLabel), new object[] { "Hi" });
  46.        
  47. Del Label = delegate(String k) { label1.Text = k; };
  48. Label("hi");   // runs in the same thread
  49.        
  50. Del Label = delegate(String k) { label1.Text = k; };
  51. this.Invoke(Label, new object[] {"hi"});   // runs in the UI thread