在 foreach 循环中启动一个新线程 [英] Starting a new thread in a foreach loop

查看:74
本文介绍了在 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.

这是我写的测试代码

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; }
}

我机器上的输出是

test2
test2

但我希望它是

test1
test2

我尝试将线程线更改为

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

但没有任何线程启动.

我想我只是对线程应该如何工作有一个误解.有人可以指出我正确的方向并告诉我我做错了什么吗?

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();
    }

有关详细信息,我建议您阅读 Eric Lippert 关于这个确切主题的帖子:关闭被认为有害的循环变量

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

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

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