Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadStateException: Thread has not been started when trying to join a thread

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

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?

Thanks in advance!

like image 980
user1178399 Avatar asked Nov 05 '13 16:11

user1178399


1 Answers

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

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

lambda 50 times, thus creating entirely new Threads.

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

var listOfThreads = threads.ToList();

and then use listOfThreads

like image 50
gͫrͣeͬeͨn Avatar answered Oct 25 '22 10:10

gͫrͣeͬeͨn