Is writing different TObjects in a TObjectDictionary thread safe?

I am writing an application where I am communicating with an SQL server, which provides an array of bytes in a blob field. I have a TObjectDictionary where I store objects, and each object stores the start byte and the number of bytes I need to read, and convert it to the required datatype.

The objects in the TObjectDictionary are referring to different SQL queries. So, to reduce the response time, my plan is to fire the queries at the same time, and whenever one of them finishes, it updates the global TObjectDictionary.

I know TObjectDictionary itself is not thread-safe, and if another thread would delete the object from the TObjectDictionary, I would have an issue, but this won’t happen. Also, 2 or more threads won’t be writing the same object.

At the moment I use TCriticalSection, so only 1 thread writes to objects in the dictionary, but I was wondering if this is really necessary?

>Solution :

Most RTL containers, including TObjectDictionary, are NOT thread-safe and do require adequate cross-thread serialization to avoid problems. Even just the act of adding an object to the dictionary will require protection. A TCriticalSection would suffice for that.

Unless you add all of the objects to the dictionary from the main thread before then starting worker threads that just access the existing objects and don’t add/remove objects. Then you shouldn’t need to serialize access to the dictionary.

Leave a Reply