C 字串駐留機制 通過lock來解答

2021-10-25 11:18:01 字數 682 閱讀 1357

string型別的字串在建立和初始化時系統會檢查記憶體中是否存在一樣的值,如果一樣就不會開闢新的空間,而是使用記憶體中相同字串的位址,因此在lock(string),不同執行緒同時訪問lock塊時會發生阻塞,所以lock(string)是有一定的風險的,當然這也要看具體的應用場景

此例子使用三個字串變數(2個不同名變數,乙個匿名變數),其值完全一樣,通過不同的執行緒去訪問他們

public

class

lockstring

public

void

getstr

(string hello)

}public

void

test()

).start()

;new

thread((

)=>).

start()

;new

thread((

)=>).

start()

;new

thread((

)=>).

start()

;new

thread((

)=>).

start()

;new

thread((

)=>).

start()

;}}

C 字串留用機制與Lock

因為c 的字串留用機制,下面的 string thekey1 string thekey2 if object.referenceequals thekey1,thekey2 thekey1,thekey2指向的是同乙個位址.但下面的 int thea 1 string thekey1 thea s...

關於字串駐留

首先看幾個例子 示例1 static void main 示例2 static void main 示例3 public const string s1 abc static void main 示例4 public static string s1 abc static void main 示例1...

字串駐留備忘

下面是個人的練習 字串拘留練習 by mcjeremy 宣告s1時,拘留池中沒有該字串,因此將它放進去 放進去後,string.isintered s1 將返回該字串值 string s1 abc123 宣告s2時,由於拘留池中已經有該字串存在,因此不再分配記憶體 s2和s1將指向同乙個引用 str...