Skip to content

Instantly share code, notes, and snippets.

@fluisgirardi
Last active October 2, 2021 15:10
Show Gist options
  • Save fluisgirardi/346c345057d851010d1de8bfcfe98752 to your computer and use it in GitHub Desktop.
Save fluisgirardi/346c345057d851010d1de8bfcfe98752 to your computer and use it in GitHub Desktop.
This example shows how save a bitmap in a memory stream and how to safe pass it to another thread without use locking techniques.
procedure YourClass.SaveBMP;
var
ms:TMemoryStream;
begin
//your code
ms:=TMemoryStream.Create;
yourBMP.SaveToStream(ms); //instead of save to file
yourThreadInstance.SendBMPStream(ms);
end;
//class ClassOfYourThread should have a field to the current stream;
//in this example I'll call FCurStream;
procedure ClassOfYourThread.SendBMPStream(ms:TStream);
var
aux:TStream;
begin
aux:=InterlockedExchange(FCurStream, ms);
//if aux isn't nil, the thread doesn't have processed it yet and this
//procedure updated FCurStream with another stream instance,
//so I should free the previous unprocessed stream.
if assigned(aux) then
aux.free;
end;
procedure ClassOfYourThread.Execute; //thread main loop
var
aux:TStream;
begin
while not terminated do begin
//atomic assigns nil to FCurStream and return the old value
//of FCurStream to aux;
aux:=InterlockedExchange(FCurStream, nil);
if assigned(aux) then begin
FTelegramBot.SendPictureStream(aux...); //don't remember the exact name
aux.free;
end;
end;
end;
{
Considerations:
** if the producer is faster than consumer (thread), some pictures/stream will be lost. If you don't want lost any picture/stream, replace the InterlockedExchange by TThreadList instance.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment