在一个循环中创建新线程 [英] creating new threads in a loop

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

问题描述

我试图理解为什么这个代码不工作

I'm trying to understand why this code is not working.

    private static object _lock;

    public static void Main (string[] args)
    {
        Thread thread;
        _lock = new object();

        foreach (int num in Enumerable.Range(0,5)) {
            thread  = new Thread (() => print(num.ToString()));
            thread.Start(); 
        }
    }

    public static void print(string text)
    {
        lock(_lock)
        {
            Console.WriteLine(text);
        }
    }



我最终的输出

I end up with an output of

4
1
4
4
3

4 1 4 4 3

或其他任何随机数的数字。为什么会重复的数字?

or any other random number of digits. Why does it repeat digits?

推荐答案

由于每个线程都指的是循环变量,并在没有得到自己的副本。时间创建线程

Because each thread is refering to the loop variable, and does not get its own copy at the time you create the thread.

注意,编译器警告你:访问修改封

Notice that the compiler is warning you: "Access to a modified closure".

    foreach (int num in Enumerable.Range(0,5))
    {
        int loopnum = num;

        thread = new Thread(() => print(loopnum.ToString())); 
        thread.Start();  
    }

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

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