c# - Using string as a lock to do thread synchronization -


while looking @ legacy application code noticed using string object thread synchronization. i'm trying resolve thread contention issues in program , wondering if lead strange situations. thoughts ?

private static string mutex= "abc";  internal static void foo(rpc rpc) {     lock (mutex)     {         //do     } } 

strings (from code) "interned". means instances of "abc" point same object. across appdomains can point same object (thx steven tip).

if have lot of string-mutexes, different locations, same text, lock on same object.

the intern pool conserves string storage. if assign literal string constant several variables, each variable set reference same constant in intern pool instead of referencing several different instances of string have identical values.

it's better use:

 private static readonly object mutex = new object(); 

also, since string not const or readonly, can change it. (in theory) possible lock on mutex. change mutex reference, , enter critical section because lock uses object/reference. example:

private static string mutex = "1"; private static string mutex2 = "1";  // 'lock' mutex2 , mutex same  private static void criticalbutflawedmethod() {     lock(mutex) {       mutex += "."; // hey, mutex points reference/object       // free re-enter       ...     } } 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -