Delphi read-only generics like TDictionary<T> and TList<T> are thread safe?

919 Views Asked by At

Can I add items in a Generic list or dictionary only in the unit initialization and then use it as read-only for multiple threads?

I read in a topic that TList<T> is thread safe and in another topic that TDictionary<T> is not. What would be the difference between the two?

1

There are 1 best solutions below

8
Remy Lebeau On

Reading is safe, Writing is not. As long as you can ensure the TList/TDictionary is populated before any threads access it, and you are only retrieving items, never adding/modifying items, then it is safe. However, it is best to not rely on that behavior. You should always be explicit in syncing access to shared resources across threads, such as with TCriticalSection, TMutex, TMREWSync (or Win32 SRW locks), TMonitor, etc.