The. NET uses a queue (FIFO) for TASK calls to the Task.Run method, if the calls are too close, it can use the same Thread for two Task.Run calls to boost performance. But it will always be a different Thread from the method that is calling you. Look at 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. Thread always uses a different thread. Each one can be very well used at specific points, The Task.Run you can gain performance by not needing to instantiate and start a new thread for each action, but if each action is time consuming, such as waiting for a connection via socket, may be more intentional to use the Thread itself, otherwise one action is waiting for another to be completed.
There is no guarantee that a thread is created, in fact, if one is needed it will probably be used one of the thread pool. See if this helps: http://answall.com/q/123173/101
– Maniero
@bigown Yes I understand, but for example running a series of tasks in this way in a loop, it is possible that two are executed in the same Thread simultaneously?
– Dervanil Junior
As far as I know is possible yes, but I do not know if the current implementation does it, even less I can say in which situations he would take advantage or not..
– Maniero
I understand that there can be reuse, but if two Tasks are executed in the same Thread with the same: 'Thread.CurrentThread.Managedthreadid', it can be forced to be just a Task by 'Thread.CurrentThread.Managedthreadid' ?
– Dervanil Junior
I can’t say, I have very little experience with that, but I hope someone can give you a good answer.
– Maniero