Generically, You can do as follow
- In C# 2012/Net 4.5 Create a Windows Forms Application project called Lambda1
- In the Form1 Form, insert a Label called label1
- Press F4 to open the Form1 properties (not the label1 properties)
- Click on the Events view (Icon with a thunder)
- Double click on the Form Closing event. An event handler will be created.
- Don't mind about the event handler for now. It will be replaced by another one later;
- Select and erase all the code in Form.cs (Ctrl-A/Delete key)
- Copy and paste the following code to Form1.cs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace Lambda1
{
public partial class Form1 : Form
{
System.Timers.Timer t = new System.Timers.Timer(1000);
Int32 c = 0;
Int32 d = 0;
Func<Int32, Int32, Int32> y;
public Form1()
{
InitializeComponent();
t.Elapsed += t_Elapsed;
t.Enabled = true;
}
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
c = (Int32)(label1.Invoke(y = (x1, x2) =>
{ label1.Text = (x1 + x2).ToString();
x1++;
return x1; },
c,d));
d++;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
t.Enabled = false;
}
}
}
What this code do is:
A timer is created. The Elapsed Event Handler
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
will be called every 1000ms
The label1.Text will be updated inside this event handler. Without the Invoke, there will be a thread issued
To update the label1.Text with a new value, the code was used
c = (Int32)(label1.Invoke(y = (x1, x2) => { label1.Text = (x1 +
x2).ToString(); x1++; return x1; }, c,d));
Please see that c and d are being passed as argument to x1 and x2 in the the Invoke function and x1 is returned in the Invoke call.
The variable d was inserted in this code just to show how to pass more than one variable when Invoke is called.