If I have something like this (pseudocode):
class A
{
List<SomeClass> list;
private void clearList()
{
list = new List<SomeClass>();
}
private void addElement()
{
list.Add(new SomeClass(...));
}
}
is it possible that I run into multithreading problems (or any kind of unexpected behavior) when both functions are executed in parallel?
The use case is a list of errors, which could be cleared at any time (by simply assigning a new, empty list).
EDIT: My assumptions are
- only one thread adds elements
- forgotten elements are okay (i.e. race condition between clearing and adding a new element), as long as the clear operation succeeds without problems
- .NET 2.0
There are two possibilities for problems here:
AddElementandClearListare called at the same time, you have a race condition: either the element will end up in the new list, or in the old (forgotten) one.List<T>isn’t safe for multi-threaded mutation, so if two different threads callAddElementat the same time the results aren’t guaranteedGiven that you’re accessing a shared resource, I would personally hold a lock while accessing it. You’ll still need to consider the possibility of clearing the list immediately before/after adding an item though.
EDIT: My comment about it being okay if you’re only adding from one thread was already somewhat dubious, for two reasons:
List<T>which hadn’t been fully constructed yet. I’m not sure, and the .NET 2.0 memory model (as opposed to the one in the ECMA specification) may be strong enough to avoid that, but it’s tricky to say.listvariable immediately, and still add to the old list. Indeed, without any synchronization, it could see the old value foreverWhen you add “iterating in the GUI” into the mix it gets really tricky – because you can’t change the list while you’re iterating. The simplest solution to this is probably to provide a method which returns a copy of the list, and the UI can safely iterate over that: