[C#] 纯文本查看 复制代码 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());
}
}
}
代码如上
输入结果在图片里
结果明显有同样的值,这里产生了疑问,为什么会出现同样的值呢?希望各位大大帮忙解惑!
|