Help with understanding C# syntax while Invoking a new Action

Richard picture Richard · Jul 7, 2011 · Viewed 17.2k times · Source

I am new to c# and do not understand the syntax of invoking a new action or even what an action is. From my understanding in Port1_DataReceived, I have to create an action because I am in a new tread... Can anyone elaborate on why I need to do this?

public Form1()
{
    InitializeComponent();
    SerialPort Port1 = new SerialPort("COM11", 57600, Parity.None, 8, StopBits.One);
    Port1.DataReceived += new SerialDataReceivedEventHandler(Port1_DataReceived);
    Port1.Open();
}


private void Port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
     SerialPort Port = (SerialPort)sender;
     string Line = "";
     int BytestoRead = Port.BytesToRead;
     Line = Port.ReadLine();
     label1.Invoke(new Action(() =>
     {
          label1.Text = Line;
      }));
}

The code snip that I am really having trouble understanding is:

label1.Invoke(new Action(() =>
         {
              label1.Text = Line;
          }));

Can someone break down what this is doing.. I am sure it is nothing to complicated, just that I have never seen anything like it before. The syntax that is really holding me up is ()=> the new action is pointing to the code below or something??

Answer

StriplingWarrior picture StriplingWarrior · Jul 7, 2011

This uses something known as a "lambda expression" to create an anonymous delegate that matches the signature expected by the Action constructor.

You could achieve the same effect like this:

label1.Invoke(SetText);
...
public void SetText() { label1.Text = Line; }

or like this:

label1.Invoke(new Action(SetText));
...
public void SetText() { label1.Text = Line; }

or like this:

label1.Invoke(new Action(delegate() { label1.Text = Line; }));

or like this:

label1.Invoke(delegate() { label1.Text = Line; });

or like this:

label1.Invoke(() => label1.Text = Line);

These are mostly just syntactic shortcuts to make it easier to represent an action.

Note that lambda expressions often have parameters. When there is only one parameter, the parentheses are optional:

list.ToDictionary(i => i.Key);

When there are no parameters or multiple parameters, the parentheses are necessary to make it obvious what you're doing. Hence, the () =>.