任务不会更改参数

Cap*_*pio 4 c# multithreading closures winforms task-parallel-library

我正在玩Task函数,发现一个非常奇怪的问题,我在for循环中运行Task并将参数传递给函数(i)循环计数为100.正如我所料,输出将是这样的.
1
2
3
4
5
但是我从这个函数得到的输出是
100
100
100
我的意思是它不会改变为新的参数.有关详细信息,我上传了整个项目.

下载我制作的示例程序!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        CheckForIllegalCrossThreadCalls = false;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Task.Factory.StartNew(() => button_tast());
    }
    void button_tast()
    {
        Task[] tk =new Task[100];
        for (int i = 0; i < 100; i++)
        {
            tk[i] = Task.Factory.StartNew(() => taskThread(i));
        }
        Task.WaitAll(tk);
    }
void taskThread(int i){
    listBox1.Items.Add(i);
}
}
}
Run Code Online (Sandbox Code Playgroud)

jas*_*son 8

这是因为你正在关闭循环变量.您可以将循环重写为

for (int i = 0; i < 100; i++)
{
    int taskNumber = i
    tk[i] = Task.Factory.StartNew(() => taskThread(taskNumber));
}
Run Code Online (Sandbox Code Playgroud)

你会没事的