4

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?

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
Janus007
  • 366
  • 4
  • 11

3 Answers3

7

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.

Uri Meirav
  • 3,120
  • 1
  • 17
  • 10
2

Your code uses the value of i instead of the generated random number. It does not ignore the sleep but rather sleeps between 0 and 10ms each iteration.

Try:

Thread.Sleep(sleep);
Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124
0

The sentence

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

Will create the Task and automatically start it, then will iterate again inside the for, without waiting the task to end its process. So when the second task is created and executed, the first one may be finished. I mean you are not waiting for the tasks to end:

You should try

Task t1 = Task.Factory.StartNew(() => succes(sleep)); 
t1.Wait();
Pato
  • 679
  • 8
  • 24