我有一个类似于这个的单例类
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?
}
}
}
Web 服务将调用 CallMe 方法:
[WebMethod]
public void CallMeWebService()
{
Singleton.Instance.CallMe();
}
问题: 1) m_cacheObjects 是线程安全的吗?如果在循环交互期间(在 CallMe() 中)更改了 m_cacheObjects(由于计时器)会发生什么?
2) 调用 Webservice CallMeWebService() 时是否会创建一个新线程?