Task ignores Thread.Sleep

trying to capture the TPL.

Just for fun, I tried to create some Random Sleep Quests to see how it was handled. I aimed at the fire and forgot the drawing.

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 prints all lines to the console, ignoring Sleep (random)

Can someone explain this to me?

+4
source share
3 answers

Important:

Task TaskScheduler default TPL does not guarantee Thread for Task - a single thread can be used to process several tasks.

Calling Thread.Sleep may affect the performance of other tasks.

You can create your task using the TaskCreationOptions.LongRunning hint so that TaskScheduler will assign a dedicated thread to the task and it will be safe to block it.

+6
source

Instead of the generated random number, your code uses the value i . He does not ignore sleep, but sleeps between 0 and 10 m every iteration.

Try:

 Thread.Sleep(sleep); 
+2
source

Sentence

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

It will create a task and run it automatically, and then repeat again in the for field, without waiting for the task to complete. Therefore, when the second task is created and executed, the first can be completed. I mean, you are not expecting tasks to complete:

You must try

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

All Articles