参见英文答案 > Captured variable in a loop in C# 8个
我想要做的很简单,
我扫描一个字符串列表,然后,我将每个字符串传递给一个新的线程进行打印.
using System;
using System.Collections.Generic;
using System.Threading;
namespace MultithreadingSynchronization
{
class Program
{
static void Main(string[] args)
{
List<string> stringList = new List<string> { "server1", "server2", "server3", "server4", "server5", "server6", "server7", "server8", "server9"};
foreach (string server in stringList)
{
ThreadStart work = delegate { Threadjob(server); };
new Thread(work).Start();
//Thread.Sleep(10); // 10 ms delay of main thread
}
}
public static void Threadjob(object server)
{
Console.WriteLine(server);
}
}
}
由于某种原因,有些线程接收到错误的值,因此,输出会显示一些重复的字符串,并且还会遗漏一些字符串.
我期待这个输出(顺序并不重要):
server1
server2
server3
server4
server5
server6
server7
server8
server9
但是,有时我得到这个:
server3
server2
server5
server5
server7
server4
server8
server9
server9
有时我得到这个:
server2
server2
server4
server3
server6
server7
server7
server8
server9
等等
事实上,如果我在每个线程创建后延迟,我会得到我期望得到的.
任何的想法?
解决方法:
您应该制作变量的本地副本.
试试这个:
foreach (string server in stringList)
{
string local = server;
ThreadStart work = delegate { Threadjob(local); };
new Thread(work).Start();
//Thread.Sleep(10); // 10 ms delay of main thread
}
更多信息:Captured variable in a loop in C#