C
C#8mo ago
CrosRoad95

❔ Question about getter property of list

so, i have some class containg property of type: List<string> , how can i thread-safe return this list as some kind of snapshot of current state of list? right now i'm doing it in followoing way but i'm not sure if it okey
private readonly object _lock = new();
private readonly List<string> _strings = [];
public IReadOnlyList<string> Strings {
get {
lock(_lock)
return [.._strings];
}
}
private readonly object _lock = new();
private readonly List<string> _strings = [];
public IReadOnlyList<string> Strings {
get {
lock(_lock)
return [.._strings];
}
}
5 Replies
Jimmacle
Jimmacle8mo ago
a snapshot would be a copy so looks fine at first glance i dunno if i'd make it a property, because copying a list might be expensive in terms of what a property getter should do
CrosRoad95
CrosRoad958mo ago
do you have any other idea? in theory, i need it for single iteration
Jimmacle
Jimmacle8mo ago
make it a method instead
CrosRoad95
CrosRoad958mo ago
in few places i used yield return inside lock
Accord
Accord8mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.