我正在发民使用.NET MVC数据访问层 - 静态列表对象和缓存
我有一个基本组成是从我的数据数据库中创建静态列表对象的数据访问层的站点。
重建此数据的方法首先清除所有列表对象。一旦它们是空的,然后添加数据。这是我使用的一个列表的例子。它是一种生成所有英国邮政编码的方法。大约有50的方法与此类似在我的应用程序返回的各种信息,如城镇,地区,会员,电子邮件等
public static List<PostCode> AllPostCodes = new List<PostCode>();
当重建方法被调用它首先清除列表。
ListPostCodes.AllPostCodes.Clear();
下将其重新bulilds中的数据,通过调用GetAllPostCodes()方法
/// <summary> /// static method that returns all the UK postcodes /// </summary> public static void GetAllPostCodes() { using (fab_dataContextDataContext db = new fab_dataContextDataContext()) { IQueryable AllPostcodeData = from data in db.PostCodeTables select data; IDbCommand cmd = db.GetCommand(AllPostcodeData); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = (SqlCommand)cmd; DataSet dataSet = new DataSet(); cmd.Connection.Open(); adapter.FillSchema(dataSet, SchemaType.Source); adapter.Fill(dataSet); cmd.Connection.Close(); // crete the objects foreach (DataRow row in dataSet.Tables[0].Rows) { PostCode postcode = new PostCode(); postcode.ID = Convert.ToInt32(row["PostcodeID"]); postcode.Outcode = row["OutCode"].ToString(); postcode.Latitude = Convert.ToDouble(row["Latitude"]); postcode.Longitude = Convert.ToDouble(row["Longitude"]); postcode.TownID = Convert.ToInt32(row["TownID"]); AllPostCodes.Add(postcode); postcode = null; } } }
重建时每隔1小时。这确保了网站每1小时将有一组新的缓存数据。
问题得到的是,偶尔如果在重建过程中,服务器将被一个请求命中并抛出一个异常。例外是“索引超出了数组的范围”。这是由于列表被清除时。
ListPostCodes.AllPostCodes.Clear(); - // throws exception - although its not always in regard to this list.
一旦抛出此异常,应用程序就会死亡,所有用户都将受到影响。我必须重新启动服务器才能修复它。
我有2个问题...
- 如果我使用缓存,而不是静态的物体会帮助呢?
- 有什么办法,我可以说“而重建正在发生,等待它完成,直到接受请求”
任何帮助是最appricaiated;)
truegilly
最正确的解决方案是避免静态方法,这是不好的。我的意思是,总是不好。即使你认为没问题,也要三思,因为这很糟糕。如果您使用它们,请记住Web应用程序请求可能会在单独的线程上并发执行。然后,了解静态数据和线程,并再次决定是否需要它们。 – queen3 2010-04-21 09:30:06