Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQpad thread behaviour

I was just starting out on LinqPad and trying some thread snippets in it and I was bewildered as to why my code is not doing as predicted to do.

Thread t1 = new Thread
(delegate()
    {
        for (int cycles = 0; cycles < 1000; cycles++)
        {
            Thread.Sleep(500);
            Console.WriteLine("Hello World!");
        }
    }
);
t1.Start();

Console.WriteLine("Soham");

Why is this only printing Soham. The code block inside the thread is not at all executing. I'm not able to understand why because the syntax compiles fine and as far as I I know about c# this should compile fine and run in VS2010 and execute both outputs, even though the order of which cannot be determined. What am I doing or thinking wrong here. I may need some useful tutorials and suggestions to get used to LinqPad.

like image 371
Soham Dasgupta Avatar asked Feb 21 '23 03:02

Soham Dasgupta


1 Answers

Try adding a t1.Join() after the Console.WriteLine("Soham") :-) The LINQPad probably sees the main thread terminating and kills everything. With the t1.Join(); the main thread will wait for the other thread to finish.

Ah... and just tested it :-)

I'll add that you can write in less characters:

new Thread(() => 
{
like image 107
xanatos Avatar answered Mar 02 '23 20:03

xanatos