简体   繁体   English

BackgroundWorker 中的 Thread.Sleep(0)

[英]Thread.Sleep(0) in BackgroundWorker

Is there a harm in using Thread.Sleep(0) in a BackgroundWorker thread?在 BackgroundWorker 线程中使用 Thread.Sleep(0) 是否有危害? Is there a benefit?有好处吗?

I use BackgroundWorker for things like lengthy database queries, datatable builds, https web queries, etc. These tasks sometimes take up to five seconds to complete.我将 BackgroundWorker 用于诸如冗长的数据库查询、数据表构建、https Web 查询等。这些任务有时需要 5 秒钟才能完成。 I thought I observed BackgroundWorker making the UI slightly less responsive, but I may be mistaken.我以为我观察到 BackgroundWorker 使 UI 的响应性稍差,但我可能错了。 So, I placed Thread.Sleep(0) in the BackgroundWorker code.因此,我将 Thread.Sleep(0) 放在 BackgroundWorker 代码中。 Did that actually help me?这真的对我有帮助吗? Did it hurt me?有没有伤害到我?

EDIT: I am trying to make the UI thread more responsive.编辑:我试图使 UI 线程更具响应性。 I believed that Sleep(0) would yield time to the UI thread during tight loops, and make the UI more responsive, but maybe I'm wrong.我相信 Sleep(0) 会在紧密循环期间为 UI 线程腾出时间,并使 UI 响应更快,但也许我错了。 I don't care how long the background task takes.我不在乎后台任务需要多长时间。

A benefit?好处? No, it is just a stab for a stop on 0 milliseconds .不,它只是stop on 0 milliseconds Maybe, it is useful to dynamically change the delay.也许,动态更改延迟很有用。 But I don't know a useful case for it.但我不知道一个有用的案例。

Harm?伤害? Not big, just a few OS instructions to make the stop and keep it on.不大,只是一些操作系统指令来停止并保持它。 No result but some additional work.没有结果,只有一些额外的工作。

BackgroundWorker by its definition is for heavy/long tasks that shouldn't block UI (block elements, fill your form with a single color, ...).根据其定义,BackgroundWorker 用于不应该阻塞 UI 的繁重/长任务(阻塞元素,用单一颜色填充表单,...)。 That

slightly less responsive反应稍差

behavior comes from the heavy task in the background.行为来自后台的繁重任务。 Your machine still has the same OS/RAM/CPU that should be shared between all of your threads and tasks.您的机器仍然具有相同的 OS/RAM/CPU,应该在您的所有线程和任务之间共享。 If your machine is out of free resources then existing ones will be shared in time.如果您的机器没有可用资源,那么现有的资源将及时共享。 Kind of an additional big player that pushes existing ones.一种推动现有玩家的额外大玩家。

Update.更新。 As properly noticed Solomon Slow , Sleep(0) is an equivalent for Yeld() (pass execution to another thread that is ready to run on the current processor).正如正确注意到的Solomon Slow ,Sleep(0) 是 Yeld() 的等价物(将执行传递给准备在当前处理器上运行的另一个线程)。 So it COULD slow your BG process, make it work longer.所以它可能会减慢你的 BG 过程,让它工作更长时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM