Pass each list item to a new thread one by one(将每个列表项一个一个传递给一个新线程)
问题描述
我想做的很简单,
我扫描一个字符串列表,然后将每个字符串传递给一个新线程进行打印.
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):
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
等等
确实,如果我在每个线程创建后延迟,我会得到我期望得到的结果.
indeed, if I put a delay after each thread creating, I get what I expect to get.
有什么想法吗?
推荐答案
你应该制作变量的本地副本.试试这个:
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
}
在此处了解更多信息:在 C# 循环中捕获的变量
这篇关于将每个列表项一个一个传递给一个新线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将每个列表项一个一个传递给一个新线程
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01