Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top