我有類似這樣C#辛格爾頓線程安全
public class Singleton
{
private static Singleton m_instance;
private Timer m_timer;
private static List<CustomObject> m_cacheObjects;
private Singleton()
{
m_cacheObjects = new List<CustomObject>();
m_timer= new Timer(MyTimerCallBack,
null,
TimeSpan.FromSeconds(60),
TimeSpan.FromSeconds(60));
}
public static Singleton Instance
{
get
{
if (m_instance == null)
{
m_instance = new Singleton();
}
return m_instance;
}
}
private void MyTimerCallBack(object state)
{
//******** Update the list by interval here ******************
m_cacheObjects = UpdateTheList();
}
public void CallMe()
{
foreach (CustomObject obj in m_cacheObjects)
{
// do something here based on obj
// The question is, does the m_cacheObjects is thread safe??
// what happen if the m_cacheObjects is changed
// during the loop interation?
}
}
}
的的CallMe方法的單身類將Web服務調用 1)是m_cacheObjects的線程安全?如果在循環交互期間(在CallMe()中)m_cacheObjects被更改(由於計時器)會發生什麼?
2)Webservice CallMeWebService()被調用時是否會創建一個新的線程?
1)a)否,1 )b)您不能確定,2)是 – Jodrell 2012-07-26 08:18:57
我將按照下面的回答使靜態初始化成爲線程安全的。 – user1553857 2012-07-26 08:47:47
現在我更關注靜態列表m_cacheObjects。我在foreach循環中隱式暫停(調試模式),並等待計時器打勾並更改m_cacheObjects列表,假設foreach循環將由於列表修改而失敗,但它將繼續循環而無一例外。這是正常的嗎? – user1553857 2012-07-26 08:53:51