【发布时间】:2011-02-10 12:15:39
【问题描述】:
我正在使用 .net MVC 开发一个网站
我有一个数据访问层,它基本上由从我的数据库中的数据创建的静态列表对象组成。
重建此数据的方法首先清除所有列表对象。一旦它们为空,然后添加数据。这是我正在使用的列表之一的示例。它是一种生成所有英国邮政编码的方法。在我的应用程序中有大约 50 种与此类似的方法,它们返回各种信息,例如城镇、地区、成员、电子邮件等。
public static List<PostCode> AllPostCodes = new List<PostCode>();
-
当调用rebuild方法时,它首先清除列表。
ListPostCodes.AllPostCodes.Clear();
-
接下来,它通过调用 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 个问题...
- 如果我使用缓存而不是静态对象会有所帮助吗?
- 我有什么办法可以说“在重建过程中,等待它完成,直到接受请求”
任何帮助都是最合适的 ;)
真正的吉利
【问题讨论】:
-
最正确的解决方案是避免使用不好的静态方法。我的意思是,总是很糟糕。即使你认为没问题,也要三思而后行,因为这很糟糕。如果您使用它们,请记住 Web 应用程序请求可能同时在不同的线程上。然后,了解静态数据和线程,并再次决定是否需要它们。
标签: asp.net-mvc caching data-access-layer