The lock is useless that way. You will have to use a thread-safe collection such as Will suggested, or if you don't need write access you can expose only a read only version of your list like so:
public ReadOnlyCollection<Character> Characters {
get {
lock (locker) { return this.characters.AsReadOnly(); }
}
}
These collections cannot be modified, so if your Character
type is immutable, you don't have any synchronization issues. If Character
is mutable, you have again a problem, but you would have that problem even with a thread-safe collection. I hope you're aware of that. You can also expose the property returning an IList<Character>
, but usually I find it better to tell the caller that the object is read only.
If you need write access, you could also do that by providing the appropriate methods at the scope of the CharacterManager
and synchronize them. Jesse has written a nice example on how to do this.
EDIT: SyncRoot is not present on ICollection<T>.