开发者

C# Abort()ing threads on exit for a Form

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 RC开发者_运维百科W can cause corruption or data loss."


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜