Check this function.
private static IEnumerable<string> FindAccessibleDatabases()
{
var connectionStrings = new List<string>();
Parallel.For(0, _connectionStringCollection.Count, (index, loopState) =>
{
try
{
using (var connection = new OleDbConnection(_connectionStringCollection[index]))
{
connection.Open();
connectionStrings.Add(_connectionStringCollection[index]);
}
}
catch (OleDbException)
{
}
finally
{
connection.Close();
}
});
return connectionStrings.ToList();
}
I am using Parallel.Foreach and adding values in a List from multiple databases at a time. I can use ConcurrentBag(It is tread safe while retrieving the data but adding is not mentioned) as I am just adding the data to the list, can use List.
Now if two threads try to add data to the list at exactly same time what will happen?
If it will create race condition, what if I use ConcurrentBag?
Thanks,
Omkar
You run the risk of unspecified bad things happening, like duplicates, one item not being added, corrupting the data structure, etc.
The documentation says that
List<T>‘s Add method is not thread safe (well, specifically it says:). Therefore you need to use a lock statement or other form of thread synchronization around it, or you need to switch to a thread-safe data structure, like something in the System.Collections.Concurrent namespace.
If you use ConcurrentBag’s Add method, you don’t need to worry about locking. The data structure is explicitly thread-safe.