Task is ignoring Thread.Sleep

梦想与她 提交于 2019-12-05 17:31:31

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.

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);

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!