BackgroundWorker 与后台线程 [英] BackgroundWorker vs background Thread

查看:29
本文介绍了BackgroundWorker 与后台线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于我应该在 Windows 窗体应用程序上使用的后台线程实现的选择的文体问题.目前,我在具有无限 (while(true)) 循环的表单上有一个 BackgroundWorker.在这个循环中,我使用 WaitHandle.WaitAny 来保持线程休眠,直到发生有趣的事情.我等待的事件句柄之一是StopThread"事件,以便我可以跳出循环.当从我覆盖的 Form.Dispose() 发出此事件信号时.

I have a stylistic question about the choice of background thread implementation I should use on a windows form app. Currently I have a BackgroundWorker on a form that has an infinite (while(true)) loop. In this loop I use WaitHandle.WaitAny to keep the thread snoozing until something of interest happens. One of the event handles I wait on is a "StopThread" event so that I can break out of the loop. This event is signaled when from my overridden Form.Dispose().

我在某处读到 BackgroundWorker 确实适用于您不希望与 UI 捆绑在一起并具有有限端的操作 - 例如下载文件或处理一系列项目.在这种情况下,结束"是未知的,只有当窗口关闭时.因此,为此我使用后台线程而不是 BackgroundWorker 是否更合适?

I read somewhere that BackgroundWorker is really intended for operations that you don't want to tie up the UI with and have an finite end - like downloading a file, or processing a sequence of items. In this case the "end" is unknown and only when the window is closed. Therefore would it be more appropriate for me to use a background Thread instead of BackgroundWorker for this purpose?

推荐答案

根据我对您问题的理解,您正在使用 BackgroundWorker 作为标准线程.

From my understanding of your question, you are using a BackgroundWorker as a standard Thread.

对于不想占用UI线程的事情,推荐BackgroundWorker是因为它在做Win Forms开发的时候暴露了一些不错的事件.

The reason why BackgroundWorker is recommended for things that you don't want to tie up the UI thread is because it exposes some nice events when doing Win Forms development.

RunWorkerCompleted 这样的事件在线程完成它需要做的事情时发出信号,ProgressChanged 事件更新线程进度的 GUI.

Events like RunWorkerCompleted to signal when the thread has completed what it needed to do, and the ProgressChanged event to update the GUI on the threads progress.

因此,如果您使用这些,我认为使用标准线程来完成您需要做的事情没有任何危害.

So if you aren't making use of these, I don't see any harm in using a standard Thread for what you need to do.

这篇关于BackgroundWorker 与后台线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆