Task.Run always starts a new Thread?

5

When executing a list of tasks started through Task.Run, is it guaranteed that each one is executed on a different Thread?

When reading the documentation, it seems to me that this is the default behavior, while doing the tests I was validating through Thread.CurrentThread.ManagedThreadId.

I know that threads can be reused, what I need is for each to execute only one Task, in isolation, not running two Tasks on the same Thread.

    
asked by anonymous 10.08.2016 / 21:43

1 answer

1
.NET uses a queue (FIFO) for TASK calls to the Task.Run method, if the calls are too close, it can use a same Thread for two Task.Run calls to increase performance. But it will always be a Thread different from the method that is calling it. Here's an example:

 static void Main(string[] args)
        {
            Console.WriteLine("Id Main: " + Thread.CurrentThread.ManagedThreadId);
            for (int i = 0; i < 100; i++)
            {
                Task.Run(() =>
                {
                    Console.WriteLine("Id Run " + i + ": " + Thread.CurrentThread.ManagedThreadId);
                });
            }

            for (int i = 0; i < 100; i++)
            {
                var t = new Thread(() =>
                {
                    Console.WriteLine("Id Thread " + i + ": " + Thread.CurrentThread.ManagedThreadId);
                });
                t.Start();
            }

            Console.ReadKey();
        }

In this example you see that some Task.Run use the same thread. The Thread class always uses a different thread. Each one can be very well used in specific points, The Task.Run you can gain performance for not having to instanciate and to initiate a new thread for each action, but if each action is delayed, as for example I wait for a connection via socket , it may be more intentional to use the Thread itself, otherwise one action is waiting for another to complete.

    
30.08.2016 / 20:40