Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task is ignoring Thread.Sleep

trying to grasp the TPL.

Just for fun I tried to create some Tasks with a random sleep to see how it was processed. I was targeting a fire and forget pattern..

static void Main(string[] args)
    {
        Console.WriteLine("Demonstrating a successful transaction");

        Random d = new Random();
        for (int i = 0; i < 10; i++)
        {
            var sleep = d.Next(100, 2000);


            Action<int> succes = (int x) =>
            {
                Thread.Sleep(x);
                Console.WriteLine("sleep={2}, Task={0}, Thread={1}: Begin successful transaction",
                   Task.CurrentId, Thread.CurrentThread.ManagedThreadId, x);
            };

            Task t1 = Task.Factory.StartNew(() => succes(sleep));
        }
        Console.ReadLine();
    }

But I don't understand why it outputs all lines to the Console ignoring the Sleep(random)

Can someone explain that to me?

like image 692
Janus007 Avatar asked Jan 22 '23 04:01

Janus007


1 Answers

Important:

The TPL default TaskScheduler does not guarantee Thread per Task - one thread can be used for processing several tasks.

Calling Thread.Sleep might impact other tasks performance.

You can construct your task with the TaskCreationOptions.LongRunning hint this way the TaskScheduler will assign a dedicated thread for the task and it will be safe to block on it.

like image 97
Uri Meirav Avatar answered Jan 28 '23 19:01

Uri Meirav