简体   繁体   English

暂停和恢复BackgroundWorker

[英]Pausing and resuming BackgroundWorker

I've been wondering is there any way in which we can move BackgroundWorker to sleep and resume it again just like thread. 我一直想知道有什么方法可以使BackgroundWorker进入睡眠状态并像线程一样再次恢复它。 I've searched in many forums in vain. 我徒劳地搜索了许多论坛。 None of them show any method which would do that. 他们都没有显示任何可以做到这一点的方法。 I checked Microsoft documentation and found out there isn't any predefined methods. 我检查了Microsoft文档,发现没有任何预定义的方法。

I know the workarounds by using resetEvents. 我知道通过使用resetEvents的解决方法。 Just asking for any other possible and much easier way. 只是要求任何其他可能且容易得多的方法。

If you use Task instead of BackgroundWorker you can use the PauseTokenSource . 如果使用Task而不是BackgroundWorker,则可以使用PauseTokenSource

This class is similar to the built in CancellationTokenSource only suitable for pausing tasks and not canceling them. 此类类似于内置的CancellationTokenSource,仅适用于暂停任务而不是取消任务。

PauseTokenSource API was built exactly for what you need and it's API can replace your usage of Thread.Sleep and all the signaling events. PauseTokenSource API正是根据您的需要而构建的,并且该API可以替代您对Thread.Sleep和所有信令事件的使用。

Other option besides PauseTokenSource can use AsyncManualResetEvent , the mechanism internal is quite similar but they differ in the API. 除了PauseTokenSource之外,其他选项也可以使用AsyncManualResetEvent ,其内部机制非常相似,但API有所不同。 I think that PauseTokenSource is much more convenient and especially built for this purpose, more info here . 我认为PauseTokenSource更加方便,特别是为此目的而构建的,更多信息在此处

From within your DoWork handler, you can call Thread.Sleep() whenever you want. DoWork处理程序中,您可以随时调用Thread.Sleep() If you want, from the GUI, to be able to signal the worker to pause, set up a concurrent queue, feed your sleep requests into it from the GUI thread, and have your DoWork handler check the queue periodically, pausing as requested. 如果您希望从GUI发出信号来指示工作人员暂停,设置并发队列,将睡眠请求从GUI线程馈入该队列,并让您​​的DoWork处理程序定期检查该队列,并根据请求暂停,则可以发出信号。

(If you want to pause the BackgroundWorker until signaled again rather than for a certain period of time, you can do that in a similar way--just periodically check the queue for a "restart" command and sleep a few milliseconds before checking again.) (如果要暂停BackgroundWorker 直到再次发出信号,而不是在特定时间段内暂停,则可以通过类似的方式执行此操作-只需定期检查队列中的“重新启动”命令,并在重新检查之前休眠几毫秒。 )

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

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