c# - Object locks instance member to synchronize access to it -


this question has answer here:

is neccessary create placeholder lock object thread-safety (and correctness) or sufficient lock on resource (assuming no other code need it).

locking system.random

private static readonly random rnd = new random(); public static int rand(int min, int max) {     lock(rnd) {         return rnd.next(min, max);     } } 

using separate placeholder/dummy lock object

private static readonly random rnd = new random(); private static readonly object rndlock = new object() public static int rand(int min, int max) {     lock(rndlock) {         return rnd.next(min, max);     } } 

this may seem trivial i'm concerned if first code-block susceptible deadlock or other issues

the reason avoid locking object itself, avoid situation lock taken inadvertently, if "object itself" publicly exposed. if using "object itself" inside private class or method, there no harm in using method propose.


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -