Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# asynchronous delegates, thread scheduling

I'm absolutely new to threads and trying to understand the very basics. I've got this code with asynchronous delegates invocation:

static void Main(string[] args)
{      
   Action<Thread, string> action = (mainThread, name) =>
        {
            Thread.CurrentThread.Name = name;
            Thread.CurrentThread.IsBackground = false;
            Console.WriteLine("Thread {0} starts", Thread.CurrentThread.Name);
            while (true)
            {
                var input = Console.ReadLine();
                Console.WriteLine("Thread {0} catches an input. User's input is: \"{1}\""
                                  +"\nMain thread is alive = {2}",
                                  Thread.CurrentThread.Name, input, mainThread.IsAlive);
            }
        };
    action.BeginInvoke(Thread.CurrentThread,"First", null, null);
    action.BeginInvoke(Thread.CurrentThread, "Second", null, null);
    Thread.Sleep(2000);
}

And whatever I do, the output result always goes in the following order: First->Second->First->Second->First...

output

As far as I understand, the output order should be nondetermenistic. Bu in this case it is. How the thread queue is processed? What am I missing? Please, explain

like image 616
user3101007 Avatar asked Nov 27 '25 12:11

user3101007


1 Answers

When you wait for input from the user on var input = Console.ReadLine(); you are basically locking your threads. the first one waits for input and when received prints it. The other thread at the exact time already asked for input and waiting for it. So you get one line for each one.

If you remove the ReadLine and use this line instead:

var input = "Hamster";

You will get the results you want:

enter image description here

like image 152
i3arnon Avatar answered Nov 29 '25 04:11

i3arnon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!