In .NET when Aborting Thread, can this piece of code get corrupted?
Little intro:
In complex multithreaded aplication (enterprise service bus ESB), I need to use Thread.Abort, because this ESB accepts user written modules which communicates with hardware security modules. So if this module gets deadlocked or hardware stops responding - i need to just unload this module and rest of this server aplication must keep runnnig.
So there is abort sync mechanism which ensures that code can be aborted only in user section and this section must be marked as AbortAble. If this happen (abort) there is possibility that ThreadAbortException will be thrown in this pieace of code:
public void StopAbortSection()
{
var id = Thread.CurrentThread.ManagedThreadId;
lock (threadIdMap[id])
{
....
}
}
For example module is in AbortSection (entered by calling similar method StartAbortSection) and ServerAplication decides to abort user module, but after this decision but before actual Thread.Abort, module enters NonAbortableSection by calling this method, but lock is actualy taken on that locking object.
So lock will block until Abort is executed but abort can be executed also before reaching this block in this code. But Object with this method is essential and i need to be sure that this pieace of code is safe to abort in any moment (doesnt get corrupted - for example i dont know what happens when reading from Dictionary.开发者_开发百科.).
So i have to mention that threadIdMap is Dictionary(int,ManualResetEvent), and locking object is instance of ManualResetEvent.
I hope you now understad my question. Sorry for its largeness.
What do you mean by the exception being "violated"?
The ThreadAbortException can be thrown anywhere in the code. The lock doesn't affect that at all, unless it's one thread that is aborting another, the code to abort a thread is inside the lock, and the threads lock on the same object.
The threads have to lock on the same object to be effective. Unless you have different items in the dictionary that contain references to the same ManualResetEvent objects, the lock is totally useless.
精彩评论