@moshenti
I want to interrupted the thread because TThread.terminate waste much time of cpu and I don't have any control in internal operation
I suppose the p.LoadFromFile('3.jpg') takes to much time/resource, so load the jpg in chunks, allowing the thread to exit whenever it's needed, like this:
procedure TTestThread.Execute;
const
BufferSize = 1048576; //set whatever value you find appropriate
var
Fs: TFileStream;
Ms: TMemoryStream;
TotalCount: Int64;
BytesToRead: Integer;
Buffer: PByte;
begin
Fs := TFileStream.Create('3.jpg', fmOpenRead or fmshareDenyWrite);
try
TotalCount := 0;
Ms := TMemoryStream.Create;
try
Ms.SetSize(Fs.Size);
GetMem(Buffer, BufferSize);
repeat
if FNeedToBreak then //<- this is the most important part
Break;
if TotalCount + BufferSize > Fs.Size then
BytesToRead := FS.Size - TotalCount
else
BytesToRead := BufferSize;
Fs.Read(Buffer^, BytesToRead);
Ms.Write(Buffer^, BytesToRead);
TotalCount := TotalCount + BytesToRead;
until TotalCount >= FS.Size;
FreeMem(Buffer);
Ms.Position := 0;
//do other small operations here, every loop must contain the: "if FNeedToBreak then Break;" part
finally
Ms.free;
end;
finally
Fs.Free;
end;
end;
Start your thread:
tt := TTestThread.Create(True);
tt.FreeOnTerminate := True;
tt.Start;
When you want to terminate the thread immediately, just do this:
tt.NeedToBreak := True;
tt.Terminate;
PS: And make sure you use the synchronize method when updating the GUI, otherwise bad things start to happen quickly. Even better, you should use queues to update the main thread since is asynchronous, but be careful when closing the main form not to cause deadlock.