C# 在表单退出时中止 (Abort()ing) 线程

发布于 2024-08-30 11:36:21 字数 497 浏览 1 评论 0原文

到目前为止,我在单击 X 按钮时运行了此代码,但我不确定这是否是退出时终止表单上线程的正确方法。

           Type t = this.GetType();
           foreach (PropertyInfo pi in t.GetProperties())
           {
                if (pi.GetType() == typeof(Thread))
                {
                    MethodInfo mi = pi.GetType().GetMethod("Abort");
                    mi.Invoke(null, new object[] {});
                }   
            }

我不断收到此错误:“尝试释放正在使用的 RCW。RCW 正在活动线程或另一个线程上使用。尝试释放正在使用的 RCW 可能会导致损坏或数据丢失。”

So far I have this code run when the X button is clicked, but I'm not sure if this is the correct way to terminate threads on a form on exit.

           Type t = this.GetType();
           foreach (PropertyInfo pi in t.GetProperties())
           {
                if (pi.GetType() == typeof(Thread))
                {
                    MethodInfo mi = pi.GetType().GetMethod("Abort");
                    mi.Invoke(null, new object[] {});
                }   
            }

I keep getting this error: "An attempt has been made to free an RCW that is in use. The RCW is in use on the active thread or another thread. Attempting to free an in-use RCW can cause corruption or data loss."

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

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

发布评论

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

评论(1

君勿笑 2024-09-06 11:36:21

显然,这不是中止该特定线程的正确方法,异常告诉您这一点。该消息表明您正在该线程上使用 COM 对象。也许像 Microsoft Excel 之类的东西?在工作线程上运行 COM 对象很麻烦,它们通常有严格的线程要求。其中之一是它们不是线程安全的并且具有“公寓线程”亲和力。 “无论如何,对对象的所有方法调用都将在 UI 线程上运行”是一个昂贵的词。这使得它变得更慢,完全抵消了线程的优点。

无论如何,不​​要使用反射来找回线程,直接使用类中的 Thread 字段。并确保以受控的方式关闭线程,而不是拉地毯。 此线程显示了一个示例。

Clearly it is not the right way to abort that particular thread, the exception tells you so. The message shows that you are using a COM object on that thread. Maybe something like Microsoft Excel? Running COM objects on a worker thread is troublesome, they very commonly have strict threading requirements. One of which is that they are not thread-safe and have "apartment threading" affinity. An expensive word for "all your method calls on the object will run on the UI thread anyway". Which makes it slower, defeating the advantages of threading completely.

Anyhoo, don't use Reflection to find your threads back, use the Thread field in your class directly. And make sure you shut down the thread in a controlled way rather than pulling the rug. This thread shows an example.

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