如何暂停BackgroundWorker?或者类似的东西
我使用 BackgroundWorker
通过在循环内调用 WebClient.DownloadString
来下载一些网站。我希望用户可以选择在下载过程中取消,因此每当我发现 CancellationPending
在循环中间打开时,我都会调用 CancelAsync
。
但现在我注意到函数 DownloadString
有时会冻结,所以我决定使用 DownloadStringAsync
(所有这些都在使用 BackgroundWorker
创建的另一个线程内) )。由于我不想在调用 DownloadStringAsync
后退出循环和函数来重写整个代码,因此我在调用它后立即创建了一个 while 循环,除了检查变量 < code>bool Stop 当调用 DownloadStringCompleted
事件处理程序或用户请求取消操作时,我会变为 true。
现在,奇怪的是它在调试版本上运行良好;但在第一个版本中,程序在 while 循环中冻结,就像它是主线程一样。
I was using a BackgroundWorker
to download some web sites by calling WebClient.DownloadString
inside a loop. I wanted the option for the user to cancel in the middle of downloading stuff, so I called CancelAsync
whenever I found that CancellationPending
was on in the middle of the loop.
But now I noticed that the function DownloadString
kinda freezes sometimes, so I decided to use DownloadStringAsync
instead (all this inside the other thread created with BackgroundWorker
). And since I don't want to rewrite my whole code by having to exit the loop and the function after calling DownloadStringAsync
, I made a while loop right after calling it that does nothing but check for a variable bool Stop
that I turn true either when the DownloadStringCompleted
event handler is called or when the user request to cancel the operation.
Now, the weird thing is that it works fine on the debug version; but on the release one, the program freezes in the while loop like if it were the main thread.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在我看来,你正忙着等待 while 循环。您应该使用事件信号来代替,例如。一个等待句柄。释放模式下的忙等待循环很可能会耗尽所有 CPU,给人一种冻结的感觉。
在 DownloadStringCompleted 中或用户取消下载时向 WaitHandle 发出信号。
检查 WaitHandle 类的 MSDN 文档。那里还有一个例子。
Sounds to me you are busy-waiting with a while loop. You should use event signaling instead, eg. a WaitHandle. A busy-waiting loop in release mode might very well consume all your cpu, giving a feeling of a freeze.
Signal the WaitHandle in DownloadStringCompleted or if the user cancels the download.
Check the MSDN docs on the WaitHandle class. There's also an example there.
发送正在检查取消的 while 循环休眠一小会儿(几毫秒)。这很好地释放了其他线程和进程的 CPU 运行时间。
Send your while loop that is checking for the cancelation to sleep for a short while (some ms). This well free up the CPU runtime for other threads and processes.
不错的话题,我用过
在我的后台工作进程中
,我有一个暂停按钮,当我按下它时,pauseWorker(全局变量或属性)变为true并仅在第一个while中循环,而不增加icounter,当我使pauseworker=再次为 false 过程继续
nice topic, i used
In my background worker process a double while
And i have a button pause, that when i press it, pauseWorker (Global variable or property) becomes true and loops in the first while only, without increasing the icounter, and when i make the pauseworker=false again the process continues