2011-11-04 33 views
0

假設我有一個控件和字符串的字典。如果我運行後臺工作器,使用控件引用訪問與控件相對應的字符串是否線程安全?在後臺工作線程安全中使用對控件的引用嗎?

Dictionary<Control, string> _ctlDict; 
//Called in the main thread 
public void Persist() 
{ 
    foreach (var control in Controls) 
    { 
    _ctlDict.Add(control, control.Name); 
    } 
} 

//Called in the background worker 
public string GetControlName(Control ctl) 
{ 
    return _ctlDict[ctl]; 
} 

這應該是好的,因爲我沒有使用任何控件的屬性 - 我只是使用控件的引用,對吧?

回答

1

只要你不訪問控件的屬性或方法,是的,它是完全安全的。它只是一個對象引用,它指向一個控件無關緊要...

+0

我這麼認爲,謝謝你的回答! –

0

唯一需要確定的是Persist和GetControlName不能同時調用。

+0

嗯,我甚至在開始背景工作之前就打電話給我。 –

相關問題