Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper thread termination in multi-threaded C# application

I have what I think is a rather complex problem. I have a C# application that utilizes a plug-in architecture using reflection. The application loads plug-in dlls and the user is able to enable/disable them. When a plug-in is enabled, the main app starts a thread to run the plug-in in. In many cases the plug-in may have multiple threads of its own. When I want to disable a plug-in I am calling Thread.Abort(). This seems to kill the initial thread that was created for the plug-in, but any additional threads that the plug-in created continue running. Is there a better way to stop all of the associated plug-in's threads along with the main thread?

Thanks.

like image 783
Brian Avatar asked Dec 04 '25 21:12

Brian


2 Answers

Don't use Thread.Abort for this purpose.

Add a Shutdown method or similar to your plugin API and ask your plugins to shutdown cleanly. If you need to protect yourself against rogue plugins that refuse to shutdown then run them in their own AppDomain and kill the AppDomain if necessary.

like image 64
Mark Byers Avatar answered Dec 07 '25 11:12

Mark Byers


I would set a flag in the plugin that I wish to close it, and the plugin itself should periodically check to see if the flag is set and if so, it should clean up after itself. This aproach works best with a while(true) {...} kind of thread body.

If instead you're using an event-based aproach with a lot of WaitForSingleObject, I would use an event that I'd pulse when I want the plugin to shut down, and I'd add the event to a WaitForMultipleObjects list to be checked.

It really depends on how your plugin is running and how exactly it's coded. Try providing more information.

Thread.Abort is a horrible way to do it, it doesn't run any cleanup at all.

like image 34
Blindy Avatar answered Dec 07 '25 09:12

Blindy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!