【发布时间】:2012-09-01 16:44:08
【问题描述】:
我需要在线程中运行具有给定参数的方法。我注意到,当我运行它时,
参数错误。对于给出的示例,我有一个数组int[] output,其数字为 1-7。对于每个数字,我使用方法WriteInt(i) 创建一个线程。我希望输出以任何顺序为 1-7,但我始终看到一些数字丢失而另一些数字重复。发生了什么以及启动这些线程的正确方法是什么?
(该列表仅用于之后加入线程)
class Program
{
static void Main(string[] args)
{
int[] output = { 1, 2, 3, 4, 5, 6, 7 };
List<Thread> runningThreads = new List<Thread>();
foreach (int i in output)
{
Thread thread = new Thread(() => WriteInt(i));
thread.Start();
runningThreads.Add(thread);
}
foreach(Thread t in runningThreads)
{
t.Join();
}
}
private static void WriteInt(int i)
{
Console.WriteLine(i);
}
}
示例输出:
3
3
4
5
6
7
【问题讨论】:
-
尝试并行 foreach。这样您就不会创建更多线程并最终造成性能威胁。
-
不幸的是,我们被困在没有并行 foreach 的 .net 3.5 上。
标签: c# multithreading .net-3.5