为什么这些任务开始延迟?(Why these tasks are starting delayed?)

编程入门 行业动态 更新时间:2024-10-27 13:27:30
为什么这些任务开始延迟?(Why these tasks are starting delayed?)

我正在尝试这段代码(只产生一些任务并模拟工作):

var tasks = Enumerable.Range(1, 10).Select(d => Task.Factory.StartNew(() => { Console.Out.WriteLine("Processing [{0}]", d); Task.Delay(20000).Wait(); // Simulate work. Here will be some web service calls taking 7/8+ seconds. Console.Out.WriteLine("Task Complete [{0}]", d); return (2 * d).ToString(); })).ToList(); var results = Task.WhenAll(tasks).Result; Console.Out.WriteLine("All processing were complete with results: {0}", string.Join("|", results));

我期待在控制台中同时看到10个Processing ... 但是当我跑步时,我最初看到了这个输出

Processing [1] Processing [2] Processing [3] Processing [4]

然后1/2秒后Processing [5] , Processing [6]和其他一个接一个地缓慢显示。

你能解释一下吗? 这是否意味着任务正在延迟启动? 为什么?

I am trying this code (just spawn some tasks and simulate work):

var tasks = Enumerable.Range(1, 10).Select(d => Task.Factory.StartNew(() => { Console.Out.WriteLine("Processing [{0}]", d); Task.Delay(20000).Wait(); // Simulate work. Here will be some web service calls taking 7/8+ seconds. Console.Out.WriteLine("Task Complete [{0}]", d); return (2 * d).ToString(); })).ToList(); var results = Task.WhenAll(tasks).Result; Console.Out.WriteLine("All processing were complete with results: {0}", string.Join("|", results));

I was expecting to see 10 Processing ... in the console at once; but when I run, initially I see this output

Processing [1] Processing [2] Processing [3] Processing [4]

Then 1/2 seconds later Processing [5], Processing [6] and others are shown slowly one after another.

Can you explain this? Does this mean tasks are being started as delayed? Why?

最满意答案

我希望你有4个CPU核心。

让两个(cpu bond)线程争夺核心导致它需要更长的时间才能完成工作,然后让1个线程执行第一个任务,然后执行第二个任务运行。

除非另有说明,否则任务系统会假定任务运行时间短且CPU受限,并且他们将使用“无阻塞”IO。

因此,我希望任务系统默认为线程数接近核心数。

使用TaskCreationOptions.LongRunning

为TaskScheduler提供了一个提示,即保证可能需要超额认购。 Oversubscription允许您创建比可用硬件线程数更多的线程。

最后,任务不是线程,它们旨在隐藏线程的大量细节,包括控制正在使用的线程数。 创建100个任务是合理的,如果你创建的100个线程都试图同时运行,那么cpu缓存等将会非常困难。


但是,让我们回到你想要做的事情。 您的示例模拟CPU绑定工作。 您说您的任务将调用Web服务 - 这意味着它们将受IO限制。

因此,它们应该异步运行。 但是, Task.Delay(20000).Wait(); 同步等待,因此它不代表将要/应该实际发生的事情。 请参阅Gediminas Masaitis答案以获取代码示例,使用await来异步进行延迟。 但是,只要您使用更多异步代码,就需要更多地考虑锁定等问题。

如果您同时进行100次请求,则异步IO显然会更好。 但是,如果你的应用程序中只有一个“手满”且没有其他使用await ,那么TaskCreationOptions.LongRunning可能就足够了。

I expect you have 4 cpu cores.

Having two (cpu bond) threads fighting over a core leads to it taking longer to complete the work then have 1 thread doing the first task, then doing the second task run.

Until it know otherwise the task system assumes tasks are short running and CPU bound and that they will use “none blocking” IO.

Therefore I expect that the task systems defaults to the number of threads being close to the number of cores.

Using TaskCreationOptions.LongRunning

provides a hint to the TaskScheduler that oversubscription may be warranted. Oversubscription lets you create more threads than the available number of hardware threads.

And lastly tasks are not threads, they are design to hide a lot of the details of threads from you, including controlling the number of threads that are in use. It is reasonable to create 100s of tasks, if you created 100s of threads all trying to run at the same time, the cpu cache etc will have a very hard time.


However lets get back to what you are trying to do. Your example simulates CPU bound work. You say your tasks will be making calls to a web service - meaning they will be IO bound.

As such, they should be running asynchronously. However, Task.Delay(20000).Wait(); waits synchronously, so it doesn't represent what will/should actually be going on. See Gediminas Masaitis answer for a code sample using await to make the delay asynchronously. However as soon as you use yet more asynchronously code, you need to think more about locking etc.

Asynchronously IO is clearly better if you have 100s of requests going on at the same time. However if you just have a "hand full" and no other usage of await in your application then TaskCreationOptions.LongRunning may be good enough.

更多推荐

本文发布于:2023-08-02 21:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1381544.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:tasks   starting   delayed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!