How can I terminate my threads with blocking functions / procedures?

I use TThread in my application, and I have many functions that I would like to use inside it. The functions that I use take time to complete, so it is not ideal for use in threads. That's why I was wondering if there is a way, besides copying and pasting the function / procedure, and then adding (maybe adding) my terminated flags to the function. I do not want to use the TerminateThread API!

A brief example:

 procedure MyProcedure; begin // some work that takes time over a few lines of code // add/inject terminated flag?! // try... finally... end; procedure TMyThread.Execute; begin MyProcedure; // or copy and paste myprocedure end; 

So, is there an efficient way to write procedures / functions that help me with the terminated flag? In addition, the procedures / functions must be global, so other functions / procedures may also call them.

+4
source share
1 answer

One option is to introduce a callback method in your procedure call. If the callback method is assigned (when calling from the stream), make a call and perform an action.

When calling MyProcedure from another location, pass nil to the procedure.

 Type TAbortProc = function : boolean of object; procedure MyProcedure( AbortProc : TAbortProc); begin //... if (Assigned(AbortProc) and AbortProc) then Exit; //... end; function MyThread.AbortOperation : Boolean; begin Result := Terminated; end; 

The reason I avoid passing a thread reference instead of a callback method is to hide the flow logic (and dependency) on MyProcedure .

+10
source

Source: https://habr.com/ru/post/1502278/


All Articles