BackgroundWorker 在执行之前就被释放了?

发布于 2024-12-10 23:16:59 字数 266 浏览 0 评论 0原文

我试图在我的应用程序中找到一个非常奇怪的错误,在寻找它的过程中,我对 BackgroundWorker 的工作原理产生了疑问。

如果我有一个如下所示的代码:

var bg = new BackgroundWorker();
bg.DoWork += MyHandler;
bg.RunWorkerAsync

是否有永远不会运行的代码?我的想法是,BG 超出了范围,并在它真正有机会运行之前被 BG 认领。

这会发生吗?

I'm trying to find a really strange bug in my application and while looking for it I've come across a doubt about how BackgroundWorker works.

If I have a code that looks like this:

var bg = new BackgroundWorker();
bg.DoWork += MyHandler;
bg.RunWorkerAsync

Is there anyway in which that would never run? What I have in mind is the bg getting out of scope and being claimed by the BG before it can actually get a chance to run.

Could that happen?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

锦欢 2024-12-17 23:16:59

如果下一行发生异常,DoWork 可能不会被调用。但我不认为这是你的问题。否则不行,RunWorkerAsnyc 将以任何方式触发执行,如果您没有更多对 BackgroundWorker 的引用,GC 也不会垃圾该实例。
检查 AsyncCompletedEventArgs.Error 属性,查看如果 DoWork 事件处理程序中发生异常。

If in the next line an exception will happen, probably the DoWork will not be called. But I don't assume this is your problem. Otherwise no, RunWorkerAsnyc will trigger the execution in any way, GC will not garbage the instance also if you don't have no more reference to your BackgroundWorker.
Check the AsyncCompletedEventArgs.Error property, to see if an exception has happened in the DoWork-eventhandler.

天涯离梦残月幽梦 2024-12-17 23:16:59

不,因为 RunWorkerAsync 应该启动新线程!

No, because RunWorkerAsync should start the new thread!

吖咩 2024-12-17 23:16:59

不,您调用 RunWorkerAsync 的事实是将工作“排队”以在单独的线程上执行,因此除了您必须引用的之外,还有对您的工作线程的引用。如果有东西保留对工人的引用,那么工人将不会被处置。更准确地说:执行工作线程的线程实例需要有一个句柄才能访问工作线程状态(这可以防止工作线程在离开作用域后被释放)。

在执行之前处理工作线程的唯一方法是,如果您自己执行某些操作来显式处理它(我想不出那可能是什么),或者在工作线程执行之前退出应用程序。

No, the fact that you called RunWorkerAsync "queues" the work for execution on a separate thread, so there is reference to your worker aside from the one you had to it. If something is keeping a reference to the worker, then the worker will not be disposed. To be more precise: the thread instance that's executing the worker needs to have a handle to it in order to access the worker state (which prevents the worker from being disposed once it leaves your scope).

The only way for the worker to get disposed before executing is if you do something to explicitly dispose it yourself (I can't think of what that could be) or if you exit the application before the worker executes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文