Identify the potential thread safety issue in the following code snippet. Explain why the original code is flawed.
.NET interview question for Advanced practice.
Answer
The issue is that List<T is not thread-safe. Concurrent calls to AddData can corrupt the list. The solution is to use a lock around the data.Add operation.
Explanation
Option B is correct. The readonly keyword prevents the data field from being reassigned to a new list, but it does not make the List<T object itself thread-safe. List<T is not designed for concurrent modifications. If multiple threads call AddData at the same time, a race condition can occur, potentially corrupting the internal array of the list and leading to data loss or exceptions. The standard solution is to wrap the modification in a lock statement to ensure only one thread can modify the list at a time. Corrected Code: csharp public class DataCache { private static readonly List<string data = new List<string(); private static readonly object lock = new object(); public static void AddData(string item) { lock (lock) { data.Add(item); } } }