views:

208

answers:

1

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."

+2  A: 

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.

Hans Passant
I've always wondered why it was always faster while the window was minimized. The COM object is a flash game and whenever I run an infinite loop on the GUI thread, the game freezes up, so I ran the loops on separate threads.
Gio Borje