一般的に、次のようにすることができます
- C# 2012/Net 4.5 で、Lambda1 という Windows フォーム アプリケーション プロジェクトを作成します。
- Form1 フォームに、label1 というラベルを挿入します。
- F4 を押して Form1 プロパティ (label1 プロパティではありません) を開きます。
- [イベント] ビュー (雷のアイコン) をクリックします。
- Form 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)
1000ミリ秒ごとに呼び出されます
label1.Text は、このイベント ハンドラー内で更新されます。Invoke がなければ、スレッドが発行されます。
label1.Text を新しい値で更新するために、コードが使用されました
c = (Int32)(label1.Invoke(y = (x1, x2) => { label1.Text = (x1 +
x2).ToString(); x1++; return x1; }, c,d));
Invoke 関数で c と d が引数として x1 と x2 に渡され、x1 が Invoke 呼び出しで返されることを確認してください。
変数 d は、Invoke が呼び出されたときに複数の変数を渡す方法を示すために、このコードに挿入されています。