Multithreading – Delphi pointer and memory release
I am using custom windows messages to exchange information from the worker thread to the form in the main VCL thread Whenever I need to send some data by message, I do this:
type PntStr = ^string;
Then post message ()
var pointString : PntStr; (...) New(pointString); pointString^ := mystring; PostMessage(frmDest.Handle,UM_THREADMSG,UM_MYEVENT1,LPARAM(pointString));
On the receiving form
try myStrP := PntStr(MSG.LParam); myfunction(myStrP^); finally Dispose(myStrP); end;
Is this the correct way to handle memory allocated by pointers? Can I free memory by calling dispose() on the pointer?
Solution
Yes, your method is correct in memory management New and dispose handle managed types correctly This is what they exist
Some nuances:
>Check the return value of PostMessage If it fails, the message is not published and the thread needs processing memory. > Do not use the handle of the form as the recipient There are competitive conditions You can recreate the form window while publishing the message Then the message will be lost If you reuse the handle, or worse, send it to a different window Or worse, you can recreate the window on the wrong thread Instead, use allocatehwnd to create a window handle that you can control its life. > Your attempt / end was wrong The attempt should occur after getting the resource This is one of the most common mistakes we see here In your code, it may be benign because the assignment cannot throw an exception, but it is still worth accuracy