How to read a file in a TTask? (Delphi, fmx)

  

I need to read bitmap files and then copy them in an image component. I would like to do this in a TTask to keep the GUI responsive. If I run the minimized code below, then sometimes the apple image appears correctly and sometimes it appears without content (a grey square). If I put the bmp.LoadFromFile(..) in the TThread.Synchronize, then it seems to works fine, but is it necessary to put it in the TThread.Synchronize?
I do not understand why it does not work as is, because 1) if I look at the source code of LoadFromFile then the procedure starts with TMonitor.Enter(Self); and 2) when I save the bmp twice as commented out in the code, then the first save always contains the correct image (so the LoadFromFile seems to work), but the second save sometimes gives the correct image and sometimes a black image (but with the correct size)?
I am new to threading, so am hoping that someone can shed some light on this and what the correct way is to read images in a TTask. I am using Delphi 10.3.3.
Thanks,
Gerard
procedure TForm1.Button3Click(Sender: TObject);
begin
TTask.Run(procedure
var bmp: TBitmap;
begin
bmp := TBitmap.Create;
bmp.LoadFromFile(‘apple.bmp’);
// bmp.SaveToFile(‘apple1.bmp’);
// bmp.SaveToFile(‘apple2.bmp’);

TThread.Synchronize(nil,
procedure
begin
Form1.Image1.bitmap.CopyFromBitmap(bmp, Rect(0, 0, bmp.Width, bmp.Height), 100, 100 );
end);

bmp.Free;
end);
end;

Comments are closed.