Proper thread termination in a multithreaded C # application

I have what I consider to be a rather difficult problem. I have a C # application that uses a plugin architecture using reflection. The application loads the DLL plugins, and the user can enable / disable them. When the plug-in is turned on, the main application launches the thread to start the plug-in. In many cases, a plugin can have several threads of its own. When I want to disconnect the plug-in, I call Thread.Abort (). This seems to kill the initial thread that was created for the plug-in, but any additional threads that the created plug-in continues to work. Is there a better way to stop all related streams of connected files along with the main stream?

Thank.

+3
source share
7 answers

Do not use Thread.Abortfor this purpose.

Add a method Shutdownor similar to your plugin API and ask the plugins to disconnect. If you need to protect yourself from rogue plugins that refuse to disable, run them in your own AppDomain and destroy the AppDomain if necessary.

+7
source

I would set a flag in the plugin that I would like to close, and the plugin itself should periodically check if the flag is set, and if so, it should clear after itself. This aproach works best with the body while(true) {...}.

aproach WaitForSingleObject, , , , , WaitForMultipleObjects, .

, . .

Thread.Abort - , .

+1

, Abort. ManualResetEvent, , , . :

ManualResetEvent _stopping = new ManualResetEvent(false);
...
while (!_stopping.WaitOne(0))
{
    ...
}

, :

public void Stop()
{
    _stopping.Set();
}

Thread.Join, . , Abort.

AppDomain , . , , , .

+1

-, Thread.Abort . , , . , Thread.Abort.

, , - , , .

0

, , , . , approriate API- . , Shutdown Terminate , , .

, ( ), - , , , , , . . .

0

, , , , .
, , . Thread.Abort(), ThreadAbortException.

Thread.Abort() . , , . , Thread.Interrupt() , WaitSleepJoin ( WaitHandle, ..) . ThreadInterruptedException. .

0

The other guys have the correct code in the graceful shutdown signal. However, if you cannot easily change the code of the child threads, and you are under terrible graphic pressure, and if there is little chance that the child threads will be reset or paused, and you promise to reorganize this later, then you can add to your The plugin is fault tolerant, which adds child threads to the collection, and then catch a ThreadAbortException and skip the collection that interrupts the child threads.

0
source

Source: https://habr.com/ru/post/1742524/


All Articles