ThreadStateException:尝试加入线程时尚未启动线程 [英] ThreadStateException: Thread has not been started when trying to join a thread

查看:64
本文介绍了ThreadStateException:尝试加入线程时尚未启动线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我在一次采访中遇到了这样的问题

just recently i faced with such a question on an interview

方法计算"执行的输出将是什么:

what would be the output of methid 'Calculate' execution:

public void Calculate()
    {
        var threads = Enumerable.Range(0, 50).Select(x =>
        {
            var thread = new Thread(DoWork)
            {
                Name = x.ToString()
            };
            return thread;
        });
        foreach (var thread in threads)
        {
            thread.Start();

        }
        foreach (var thread in threads)
        {
            thread.Join();
        }
    }

    private void DoWork()
    {
        Console.WriteLine("Start()");
    }

我在VS中检查了它,很惊讶ThreadStateException抛出在"thread.Join();"行上.使用调试器,我发现该线程未启动. 看来,当我们完成第二遍foreach时,我们将处理另一个线程集合.有人可以详细解释为什么会引发异常吗?

i checked it in VS and was surprised that ThreadStateException is thrown on line 'thread.Join();'. using debugger i found out that thread is not started. it seems that when we go through the 2nd foreach we deal with another collection of threads. Can anyone please explain in details WHY exception is thrown?

提前谢谢!

推荐答案

threads是IEnumerable,而不是列表,枚举threads会调用

threads is an IEnumerable, not a list, and enumerating threads calls the

var thread = new Thread(DoWork)
{
   Name = x.ToString()
};
return thread;

lambda 50次,从而创建了全新的线程.

lambda 50 times, thus creating entirely new Threads.

如果您想将IEnumerable提炼为50个线程的具体列表,则需要调用

If you wanted to distill the IEnumerable down to a concrete list of 50 threads, you'd need to call

var listOfThreads = threads.ToList();

然后使用listOfThreads

and then use listOfThreads

这篇关于ThreadStateException:尝试加入线程时尚未启动线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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