Task 执行多任务出现问题

xx732395 2017-02-17 08:10:44
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace tasktest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
int ThreadCount = 5;
List<Task> tasklist = new List<Task>();
TaskFactory taskfactory = new TaskFactory();
for (int i = 0; i < 100; i++)
{
tasklist.Add(taskfactory.StartNew(new Action(() => {
dothreada(i.ToString());
})));
if (tasklist.Count == ThreadCount)
{
int index = Task.WaitAny(tasklist.ToArray());
tasklist.RemoveAt(index);
}
}
Task.WaitAll(tasklist.ToArray());
}

private void dothreada(string str)
{
Console.WriteLine(str.ToString());
}
}
}


代码如上,输出结果如下:

结果明显产生了相同的数值,这个问题非常疑惑,求各位大大给个解决的思路。
...全文
65 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
xx732395 2017-02-17
  • 打赏
  • 举报
回复
谢谢一楼的大哥的解答
  • 打赏
  • 举报
回复
for (int i = 0; i < 100; i++)
{
    var j = i;
    tasklist.Add(taskfactory.StartNew(new Action(() =>
    {
        dothreada(j.ToString());
    })));
..........

110,500

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧