一般地,你可以做如下
- 在C#2012/Net 4.5中创建一个名为Lambda的Windows Forms应用程序项目
- 在For M1形式,插入一个名为label1的
- 按F4打开属性Form1的(不是label1的属性)
- 点击事件视图(图标与雷霆)
- 在窗体Closing事件双击标签。一个事件处理程序将被创建。
- 现在不介意事件处理程序。稍后将由另一个取代;
- 选择并清除Form.cs中的所有代码(Ctrl-A/Delete键)
- 将以下代码复制并粘贴到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;
}
}
}
这段代码做的是:创建
计时器。经过事件处理程序
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
都会被调用1000ms的
的label1.Text将这一事件处理程序内进行更新。如果没有调用,将有发出
要使用新的值更新label1.Text一个线程,该代码使用
c = (Int32)(label1.Invoke(y = (x1, x2) => { label1.Text = (x1 +
x2).ToString(); x1++; return x1; }, c,d));
请看到,c和d是作为参数传递给Invoke函数中的x1和x2,并在Invoke调用中返回x1。
在此代码中插入变量d,以显示调用Invoke时如何传递多个变量。