C # Abort () threads on exit for a form
So far, this code has run when the X button is pressed, but I'm not sure if this is the correct way to terminate threads on the 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 was made to release an RCW that is in use. The RCW is in use on an active thread or another thread. Trying to release a used RCW may result in corruption or data loss."
a source to share
Obviously this is the wrong way to interrupt this particular thread, this explains the exception. The message indicates that you are using a COM object on this thread. Maybe something like Microsoft Excel? Executing COM objects on a worker thread is difficult and usually has strict thread requirements. One of them is that they are not thread safe and have an affinity with "apartment thread". Dear words "all calls to your method on an object will work on the UI thread anyway". This makes it slower, completely surpassing the benefits of threading.
Anyhoo, don't use Reflection to find your threads backwards, use the Thread field in your class directly. And make sure you cover the thread in a controlled manner rather than pulling on the carpet. This thread shows an example.
a source to share