I need to make sure that a thread I am creating use TThread class after a specified time will be stopped regardless if it has finished the job given or not. there is only one requirement, since this thread will try to create a condition that in an object method an infinite loop will be surfaced, there is no way to check for terminated and simple exit, I need to forcible stop the threads execution and kill it from memory.
I don't think it is possible using LCL classes/methods. You need to call OS level functions.I don't know your code but usually you can check the Terminated state inside any loop, including an infinite loop you mentioned.Juha
TMuThread.Execute;var MyTestObject : TMyObject;begin MyTestObject := TMyObject.Create(nil); Try //Set up properties // Make some modifications to protected data to hope over existing rules. // Get a Value that indirectly calls an internal method. // get a Second Value for the same reason. Terminate; Finally MyTestObject.Free; end;end;Procedure Test;var TestThread :TMyThread; ST, TK : Cardinal;begin TestThread := TmyThread.Create(True); Try TestThread.Resume; ST := GetTickcount; Repeat TK := GetTickCount - ST; Until TestThread.Terminated or (TK > 60000); If not TestThread.Terminated then //Raise Exception.Create('Infinite loop'); else //Show data retreived. Finally TestThread.Free; end;end;
Repeat TK := GetTickCount - ST; Until TestThread.Terminated or (TK > 60000);
Repeat Sleep(100); // or Sleep(1000); TK := GetTickCount - ST;Until TestThread.Terminated or (TK > 60000);
Code: [Select] Repeat TK := GetTickCount - ST; Until TestThread.Terminated or (TK > 60000);That is almost a thread in itself, and code style usually unrecommended. Unsure of this, but it might not give your behind-running-thread actual time at all. Try putting Application.Processmessages; inside the repeat..until.
I don't know enough about Win API to help you there, sorry.I wonder what you did with protected data etc., but it sounds like you are making a big hack.
You really should detect the infinite loop inside the thread itself. You know where the loops are. Just test the tick count inside them.
BTW, your main thread loop has one more problem: it hogs CPU time.You could add a Sleep there:Code: [Select]Repeat Sleep(100); // or Sleep(1000); TK := GetTickCount - ST;Until TestThread.Terminated or (TK > 60000);
//wait 6 seconds for thread to finish, if WaitForThreadTerminate(TestThread.handle,6000) <> 0 then //didn't finish, lets kill it. KillThread(TestThread.handle);