一時変数のキャプチャ。C# 5.0 の foreach の破壊的変更

qiita.com

上の記事を読んで、サンプルコードを書いてみました。

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var a = new List<Action>();
        var b = new List<Action>();
        for (int i = 0; i < 3; i++)
        {
            a.Add(() => Console.WriteLine($"[a] {i}"));

            int x = i;
            b.Add(() => Console.WriteLine($"[b] {x}"));
        }

        var c = new List<Action>();
        foreach (var e in new[] { 0, 1, 2 })
        // or foreach (var e in Enumerable.Range(0, 3))
        {
            c.Add(() => Console.WriteLine($"[c] {e}"));
        }

        foreach (var e in a) e();
        foreach (var e in b) e();
        foreach (var e in c) e();
    }
}

実行結果です。

[a] 3
[a] 3
[a] 3
[b] 0
[b] 1
[b] 2
[c] 0
[c] 1
[c] 2

Task.Run のサンプルです。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        var a = new List<Action>();
        foreach (var e in Enumerable.Range(0, 10))
        {
            Task.Run(() => Console.WriteLine(e));
        }
    }
}

実行結果です。

0
1
4
6
3
2
7
5

参考

ufcpp.net