I’m trying to get a threaded process working, but it seems to get more unstable with multiple executions. Does anyone have any ideas on how to determine what the cause is? One big difference, though, is that I’m using a blocking loop on the multiple executions instead of letting it pass through asynchronously like I have it coded to do as well.
This is the wait loop code I’m using (most obvious place to start). I need to have it this way, so TMainObject can process any events off of messages FThreadProcess sends.
procedure TMainObject.WaitForCompletion;
begin
repeat
Application.ProcessMessages;
until WaitForSingleObject(FThreadProcess.Handle, 20) = WAIT_OBJECT_0;
end;
When I take each item and process it asynchronously in separate runs, I have no problems whatsoever. Does anyone have any other ideas on things to check? Thanks.
Going only on the information available here, limited as it is, I’d have to say that Sertac Akyuz’s comment is probably on the right track. If the thread finishes while you’re processing messages, and the thread has
FreeOnTerminateset, then yourWaitForSingleObjectcall will fail in any number of different ways.To do this right, start the thread off, and then have the last thing it does be to post a message back to whichever form started it off, and put a message handler on there that kicks off the “work is complete” code.
This is yet another example of why explicit calls to
Application.ProcessMessagesshould be avoided whenever possible.