将每个列表项一个一个传递给一个新线程

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# 循环中捕获的变量

这篇关于将每个列表项一个一个传递给一个新线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将每个列表项一个一个传递给一个新线程