Pointless locking?
-
Is it pointless to put a lock around a single line of code like this (e.g. in a 'get' accessor) regardless of how _memberString is set?
lock (_locker) { return _memberString; }
probably, because there's no changes happening to the string. However, I'd be cautious to give a definitive answer, it really depends on what else the code does. Is it multi threaded ? If not, then yes, it's a waste.
Christian Graus Driven to the arms of OSX by Vista. Read my blog to find out how I've worked around bugs in Microsoft tools and frameworks.
-
Is it pointless to put a lock around a single line of code like this (e.g. in a 'get' accessor) regardless of how _memberString is set?
lock (_locker) { return _memberString; }
Better safe than not safe. :-D
-
Is it pointless to put a lock around a single line of code like this (e.g. in a 'get' accessor) regardless of how _memberString is set?
lock (_locker) { return _memberString; }
Given something like:
class c {
_locker;
_memberString;
f() {
...
lock(_locker) {
return _memberString;
}
}
}
caller() {
c v;
...
s = v.f();
}In s = v.f() _memberString will need to be copied to a temp variable, or directly to s, before f returns. By locking the return you ensure that _memberString isn't modified in mid-copy ... or at least that's the way I would expect it to work in lieu of documentation to the contrary.
...cmk The idea that I can be presented with a problem, set out to logically solve it with the tools at hand, and wind up with a program that could not be legally used because someone else followed the same logical steps some years ago and filed for a patent on it is horrifying. - John Carmack
-
Given something like:
class c {
_locker;
_memberString;
f() {
...
lock(_locker) {
return _memberString;
}
}
}
caller() {
c v;
...
s = v.f();
}In s = v.f() _memberString will need to be copied to a temp variable, or directly to s, before f returns. By locking the return you ensure that _memberString isn't modified in mid-copy ... or at least that's the way I would expect it to work in lieu of documentation to the contrary.
...cmk The idea that I can be presented with a problem, set out to logically solve it with the tools at hand, and wind up with a program that could not be legally used because someone else followed the same logical steps some years ago and filed for a patent on it is horrifying. - John Carmack
Then the issue is CAN _memberString be modified in mid-copy, under any circumstances? Consider that... 1) Strings are immutable, at least at the level of C# code. 2) _memberString is actually a reference to a string, not the string itself. References are N bytes (can't remember what N is). Perhaps it is possible that while those N bytes are being copied, the copy could be interrupted and the N bytes overwritten by a new value, so that the reference copied to s is corrupted. Like the other guy said, better safe than sorry.