Pass each list item to a new thread one by one [duplicate]

喜你入骨 提交于 2019-12-01 18:43:10
oakio

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#

new Thread(Threadjob).Start(server);

Done! However, it may be more advisable to use tasks rather than threads - or at least ThreadPool.

OK, I think I get it.
Froeach loop hold a pointer, and changes it on each iteration. Sometimes, the thread is created, but still not running. meanwhile, the loop changes the pointer at the following iteration, and when the thread starts its job, it get the current pointer's value (the subsequent string).

BTW, I found another solution here, how to pass parameters to main function of the thread, so I fixed my loop and it works properly now

foreach (string server in stringList)
{
    Thread thread1 = new Thread(new ParameterizedThreadStart(Threadjob));
    thread1.Start(server); 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!