通常,您可以执行以下操作
- 在 C# 2012/Net 4.5 中创建一个名为 Lambda1 的 Windows 窗体应用程序项目
- 在 Form1 窗体中,插入一个名为 label1 的标签
- 按 F4 打开 Form1 属性(不是 label1 属性)
- 单击事件视图(带有雷声的图标)
- 双击表单关闭事件。将创建一个事件处理程序。
- 现在不要介意事件处理程序。稍后将被另一个替换;
- 选择并擦除 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)
将每 1000 毫秒调用一次
label1.Text 将在此事件处理程序中更新。没有Invoke,就会发出一个线程
要使用新值更新 label1.Text,使用了代码
c = (Int32)(label1.Invoke(y = (x1, x2) => { label1.Text = (x1 +
x2).ToString(); x1++; return x1; }, c,d));
请注意,c 和 d 在 Invoke 函数中作为参数传递给 x1 和 x2,并且 x1 在 Invoke 调用中返回。
在这段代码中插入变量 d 只是为了说明在调用 Invoke 时如何传递多个变量。