Mega Code Archive

 
Categories / Delphi / Examples
 

Waiting for thread

Title: Waiting for thread Question: Using Sleep to rest from a thread execution can get complicated if not well used Answer: Execution of a thread can take a lot o processors time even if the code looks simple; to solve this issue most of us use a Sleep call from the Windows API. procedure Sleep(dwMilliseconds: DWORD); stdcall; Sleep call basically stop the execution for x number milliseconds (as a passed parameter. procedure TMyThread.Execute; begin While not terminated do begin {your code here...} Sleep(100); end; end; Since the Sleep call help us to release the CPU usage, allowing out program to run smoother, some of us had think that to set the parameter with a bigger value, so that the thread wait more between executions procedure TMyThread.Execute; begin While not terminated do begin {your code here...} Sleep(1000); end; end; Where is the problem? When this waiting period number get to bigger (because the should thread wait 25 seconds between execution) the application will run perfectly and smooth, but what happen when you try to exit the application. you application get stock (frozen) for a while (until the sleep execution expire) then you application will exit How to solve this problem! There are 2 basic solutions for this issue, the workaround and the well-written code. The Workaround Call Suspend before release the thread from memory then release the object MyThread.Suspend; MyThread.Free; This code is not reliable, actually in NT service pack 3 or before you will have an Access Violation Error, and the behavior in Windows 9x is totally unpredictable The Well-written code Keep your Sleep with a low value while execute your code in a controlled way with a simple local variable procedure TMyYhread.Execute; var iExec_Control : Integer; begin iExec_Control := 0; While not terminated do begin {use of an execution control variable...} if iExec_Control 10 then inc(iExec_Control) else continue; {your code here...} Sleep(100); end; end; in this way the Terminated variable can be validated more often without getting to much of the processor execution, as a result you will have a smother program without the Freeze period issue when the user exit your application. good luck, Luis Ortega