I found a solution to my problem.
First let me explain how I achieved this:
I made 2 watchdog threads that the first one recreates the 5 threads and WatchDogThread2 when terminated and the second one does the same to watchdog 1 (this took me to long because of Thread.IsAlive
was always returning true even when the thread was terminated finally used Thread.Join()
and join was working).
When one of the watchdog threads are running after a termination, it is recreating the lost one. But after 10-30 seconds and exception was thrown in a part that had no relation to watchdogs.
I retried it for many times and did some debugging.
After 30-50 tries and edit I saw that this exception is thrown in random parts of code not only the particular part.
So I started researching about the exception
ExecutionEngineException
I found out that CRL throws this when something in the code has gone wrong.
First, I thought that this issue is coused by one of the watchdogs so I changed them a few times but the error was still there (just the time until it was thrown changed a little bit).
So I removed them completely and started the program and terminated one the 5 thread.
This time nothing happened
I did this for a few more times with some edits and saw this exception happens when not using watchdogs, too. The exception came after 2-3 min instead of 10-30 seconds with the watchdogs.
I researched again and Microsoft wrote on MSDN that this was happening sometimes if a Garbage Collection was done. I disabled the Garbage Collation and recieved no longer the exception.
I wrote another thread that forced Garbage to collate every 0.5 second and saw after a thread is terminated the program received ExecutionEngineException
and crashed.
This was the solution for garbage collation so the entire process crashes and restarts / BSOD happens.
Final Solution
If a thread is terminated and garbage collection triggers, then CRL throws ExecutionEngineException
.
Just do a manual garbage collation every 0.5 sec so the program will crash and restart.
Code:
Thread t1 = new Thread(delegate () {
while (true) {
System.GC.Collect();
Thread.Sleep(500);
}
});
t1.Start();
You can start two of those threads for more security (if the user terminates t1
, garbage collection will be triggered after 0-10 mins and in this time he will do whatever you want).
3
solved How to protect threads (of my process) from termination [closed]