开始在foreach循环中一个新的线程 [英] Starting a new thread in a foreach loop

查看:312
本文介绍了开始在foreach循环中一个新的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象的名单,我想遍历该列表,并开始一个新的线程,传递当前对象。

I have a List of objects and I'd like to loop over that list and start a new thread, passing in the current object.

我已经写了什么,我认为应该做这样的一个例子,但它不工作。具体而言,它似乎像线程被覆盖掉在每次迭代。这并没有真正意义的我,但因为我在做每一次新的Thread对象。

I've written an example of what I thought should do this, but it's not working. Specifically, it seems like the threads are getting overwritten on each iteration. This doesn't really make sense to me though because I'm making a new Thread object each time.

这是考验code我写了

This is the test code I wrote

class Program
{
    static void Main(string[] args)
    {
        TestClass t = new TestClass();
        t.ThreadingMethod();
    }
}

class TestClass
{
    public void ThreadingMethod()
    {
        var myList = new List<MyClass> { new MyClass("test1"), new MyClass("test2") };

        foreach(MyClass myObj in myList)
        {
            Thread myThread = new Thread(() => this.MyMethod(myObj));
            myThread.Start();
        }
    }

    public void MyMethod(MyClass myObj) { Console.WriteLine(myObj.prop1); }
}

class MyClass
{
    public string prop1 { get; set; }

    public MyClass(string input) { this.prop1 = input; }
}

我的机器上输出的是

The output on my machine is

test2
test2

但我希望它是

but I expected it to be

test1
test2

我试图改变线程行

I tried changing the thread lines to

ThreadPool.QueueUserWorkItem(x => this.MyMethod(myObj));

但没有线程启动。

but none of the threads started.

我想我只是有一个关于如何线程都应该工作的误解。有人能指出我朝着正确的方向,告诉我,我做错了什么?

I think I just have a misunderstanding about how threads are supposed to work. Can someone point me in the right direction and tell me what I'm doing wrong?

推荐答案

这是因为你关闭了一个变量在错误的范围内。这里的解决方案是使用一个临时的在你的foreach循环:

This is because you're closing over a variable in the wrong scope. The solution here is to use a temporary in your foreach loop:

    foreach(MyClass myObj in myList)
    {
        MyClass tmp = myObj; // Make temporary
        Thread myThread = new Thread(() => this.MyMethod(tmp));
        myThread.Start();
    }

有关详细信息,我建议你阅读埃里克利珀对这个确切的主题帖子:<一href="http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx">Closing在循环变量被认为是有害

For details, I recommend reading Eric Lippert's post on this exact subject: Closing over the loop variable considered harmful

这篇关于开始在foreach循环中一个新的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆