gpt4 book ai didi

c# - 多线程时循环索引超出范围 ArgumentOutOfRangeException

转载 作者:行者123 更新时间:2023-11-30 13:24:45 24 4
gpt4 key购买 nike

我遇到了一些奇怪的行为...当我在 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
}
}

有人知道为什么会这样吗?

最佳答案

当您通过闭包将局部变量传递给线程或ThreadPool 委托(delegate)时,您需要复制该变量。如:

for (int i = 0; i < dummyText.Count; i++)
{
int index = i;
Thread t = new Thread(() => PrintThreadName(dummyText[index]));
// ...
}

如果你不这样做,那么变量基本上是通过引用传入的,索引将在 for 循环的最后超出数组的边界(这可能会发生早在执行闭包之前)。

关于c# - 多线程时循环索引超出范围 ArgumentOutOfRangeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2741870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com