【发布时间】:2011-02-14 01:45:45
【问题描述】:
我遇到了一些奇怪的行为...当我在 ThreadTest 方法中迭代 dummyText List 时,我得到一个索引超出范围异常 (ArgumentOutOfRangeException),但是如果我删除了线程我只是打印出文本,然后一切正常。
这是我的主要方法:
public static Object sync = new Object();
static void Main(string[] args)
{
ThreadTest();
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
这个方法抛出异常:
private static void ThreadTest()
{
Console.WriteLine("Running ThreadTest");
Console.WriteLine("Running ThreadTest");
List<String> dummyText = new List<string>()
{ "One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten"};
for (int i = 0; i < dummyText.Count; i++)
{
Thread t = new Thread(() => PrintThreadName(dummyText[i])); // <-- Index out of range?!?
t.Name = ("Thread " + (i));
t.IsBackground = true;
t.Start();
}
}
private static void PrintThreadName(String text)
{
Random rand = new Random(DateTime.Now.Millisecond);
while (true)
{
lock (sync)
{
Console.WriteLine(Thread.CurrentThread.Name + " running " + text);
Thread.Sleep(1000+rand.Next(0,2000));
}
}
}
这不会抛出异常:
private static void ThreadTest()
{
Console.WriteLine("Running ThreadTest");
List<String> dummyText = new List<string>()
{ "One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten"};
for (int i = 0; i < dummyText.Count; i++)
{
Console.WriteLine(dummyText[i]); // <-- No exception here
}
}
有人知道为什么会这样吗?
【问题讨论】:
标签: c# multithreading exception lambda for-loop