Wednesday, January 16, 2008

Cross Thread operations

For quiet some time now I have been using random ways to doing begin invoke. Here is a good pattern for it.

   1: public partial class Form1 : Form
   2: {
   3:     public Form1()
   4:     {
   5:         InitializeComponent();
   6:     }
   7:  
   8:     private void Form1_Load(object sender, EventArgs e)
   9:     {
  10:         ControlsHelper.SafeGui(this, delegate()
  11:         {
  12:             textBox1.Text = "using ControlsHelper on UI thread"; // this succeeds
  13:         });
  14:         Thread t = new Thread(new ThreadStart(WorkOnNewThread));
  15:         t.Start();
  16:     }
  17:     private void WorkOnNewThread()
  18:     {
  19:         ControlsHelper.SafeGui(this, delegate()
  20:         {
  21:             textBox1.Text = "using ControlsHelper"; // this succeeds
  22:         });
  23:  
  24:         textBox1.Text = "direct"; // this fails
  25:     }
  26: }
  27:  
  28: public static class ControlsHelper
  29: {
  30:     public static void SafeGui(Control control, MethodInvoker invoker)
  31:     {
  32:         if (null == invoker) return;
  33:         if (control != null)
  34:         {
  35:             if (control.InvokeRequired)
  36:                 control.BeginInvoke(invoker, null);
  37:             else
  38:                 invoker();
  39:         }
  40:         else
  41:             invoker();
  42:     }
  43: }

No comments: