What I'm trying to do is very simple,I scan a list of strings, then, I pass each string to a new thread for printing.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); } }}From some reason, there are threads that received wrong value, therefore, the output presents some duplicated strings, and also miss some strings.I'm expecting for this output (the order isn't important):server1server2server3server4server5server6server7server8server9But, sometimes I get this:server3server2server5server5server7server4server8server9server9and sometimes I get this:server2server2server4server3server6server7server7server8server9etc.indeed, if I put a delay after each thread creating, I get what I expect to get.Any idea? 解决方案 You should make local copy of variable.Try this: 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 }More info here: Captured variable in a loop in C# 这篇关于将每个列表项一个接一个地传递到新线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-13 01:58