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: }

Saturday, January 05, 2008

Language Recognition

A friend recently had to work with expressions, and he was looking around for some existing libraries which would let him do this. That's when he found ANTLR (http://www.antlr.org).

From the website :

ANTLR, ANother Tool for Language Recognition, is a language tool that provides a framework for constructing recognizers, interpreters, compilers, and translators from grammatical descriptions containing actions in a variety of target languages. ANTLR provides excellent support for tree construction, tree walking, translation, error recovery, and error reporting.

I tried to work with it ANTLR today and I think it is pretty good. One good thing about it is that it also has a GUI to write the grammar, once your grammar is ready, you can generate code in a number of languages.

My primary development language is C# so I was very happy to see that they have also explained how to tweak .csproj and compile the grammar in a visual studio project.

Lazy me

One whole week has gone by... and I have still not started "A pattern a week". I read a bit of  "Elements of Reusable Object-Oriented Software" and it has list of some simplest and most common patterns which one should start of with. They are :

  • Abstract Factory
  • Adapter
  • Composite
  • Decorator
  • Factory Method
  • Observer
  • Strategy
  • Template Method

    So for this week it is Abstract Factory.