jmod999
jmod999

Reputation: 249

Simple thread in c# not working as expected

I am following this screencast on multithreading .

The video in min 12:13 says that the program is supposed to run loop on thread with name t and then run the code from the main thread. So in the output I should see ThreadProc 0 - 9, then 4 times message from the main thread - right opposite what I have know.

Question is what is wrong. The code looks similar according to screencast.

The code:

namespace Objective_1._1 {


   internal class Program

{
    public static void ThreadMethod()
    {
        for (var i = 0; i < 10; i++)
        {
            Console.WriteLine("ThreadProc {0}", i);
            Thread.Sleep(0);
        }
    }

    public static void Main()
    {
        var t = new Thread(ThreadMethod);
        t.Start();

        // Loop on the main thread
        for (var i = 0; i < 4; i++)
        {
            Console.WriteLine("Main thread: Do some work");
            Thread.Sleep(0);
        }

       //Do not pass this line of code and exit the main until thread t finish
        t.Join();
    }
} }

When user runs it, then the result is as follows:

enter image description here

EDIT

Result with

Thread.Sleep(5)

in the main.

enter image description here

EDIT 2

Expected result:

enter image description here

Upvotes: 0

Views: 873

Answers (2)

Shar1er80
Shar1er80

Reputation: 9041

Since you're doing multithreading, there is no guarantee what order threads will run without giving a thread a higher priority over another. Just because your want your thread to run first then the main thread to finish, IMO, defeats the purpose of multithreading. You may as well not have spawned a thread to begin with. Like Yair Nevet states, the main thread just keeps running before your thread initializes and starts. For "true" multithreading, I would have expected your outputs to be mingled, but again that is not guaranteed like pm100 commented.

Now to answer your question about making the Thread finish before the main thread, move your Thread.Join() above the for loop in the main thread and you'll get the expected output that you want.

Upvotes: 2

Yair Nevet
Yair Nevet

Reputation: 13003

So in the output I should see ThreadProc 0 - 9, then 4 times message from the main thread - right opposite what I have know.

You first see the writes from the main thread because the time to initialise the child thread takes a while and starts later - In parallel, the main thread is keep running and doing its operations.

Upvotes: 0

Related Questions