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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With