ObjectDataSource.CacheDuration Свойство
Определение
Возвращает или задает длину промежутка времени (в секундах), в течение которого элемент управления источником данных кэширует данные, полученные с помощью свойства SelectMethod.Gets or sets the length of time, in seconds, that the data source control caches data that is retrieved by the SelectMethod property.
public:
virtual property int CacheDuration { int get(); void set(int value); };
[System.ComponentModel.TypeConverter(typeof(System.Web.UI.DataSourceCacheDurationConverter))]
public virtual int CacheDuration { get; set; }
[<System.ComponentModel.TypeConverter(typeof(System.Web.UI.DataSourceCacheDurationConverter))>]
member this.CacheDuration : int with get, set
Public Overridable Property CacheDuration As Integer
Значение свойства
Количество секунд, на протяжении которых объект ObjectDataSource кэширует результаты вызова свойства SelectMethod.The number of seconds that the ObjectDataSource caches the results of a SelectMethod property invocation. Значение по умолчанию равно 0.The default is 0. Значение не может быть отрицательным.The value cannot be negative.
- Атрибуты
Примеры
Этот раздел содержит два примера кода.This section contains two code examples. В первом примере кода показано, как ObjectDataSource объект поддерживает кэширование.The first code example demonstrates how an ObjectDataSource object supports caching. Во втором примере кода показано, как реализовать метод-оболочку, который возвращает DataSet объект, чтобы включить кэширование с помощью ObjectDataSource объекта.The second code example demonstrates how to implement a wrapper method that returns a DataSet object to enable caching with an ObjectDataSource object.
В следующем примере кода показано, как ObjectDataSource элемент управления поддерживает кэширование.The following code example demonstrates how an ObjectDataSource control supports caching. Чтобы включить кэширование, необходимо реализовать метод, который получает данные, определяемые SelectMethod свойством, для возврата данных в виде DataSet объекта.To enable caching, you must implement the method that retrieves data, which is identified by the SelectMethod property, to return the data as a DataSet object. В этом примере EnableCaching свойство имеет значение true
, а CacheDuration CacheExpirationPolicy Свойства и заданы.In this example, the EnableCaching property is set to true
, and the CacheDuration and CacheExpirationPolicy properties are set. ObjectDataSourceКэширует данные, возвращаемые свойством, в SelectMethod течение 30 секунд.The ObjectDataSource caches data that is returned by the SelectMethod property for 30 seconds.
<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.CS" Assembly="Samples.AspNet.CS" %>
<%@ Page language="c#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ObjectDataSource - C# Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<asp:gridview
id="GridView1"
runat="server"
datasourceid="ObjectDataSource1" />
<asp:objectdatasource
id="ObjectDataSource1"
runat="server"
typename="Samples.AspNet.CS.EmployeeLogic"
selectmethod="GetAllEmployeesAsDataSet"
enablecaching="True"
cacheduration="30"
cacheexpirationpolicy="Absolute" />
</form>
</body>
</html>
<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.VB" Assembly="Samples.AspNet.VB" %>
<%@ Page language="vb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ObjectDataSource - VB Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<asp:gridview
id="GridView1"
runat="server"
datasourceid="ObjectDataSource1" />
<asp:objectdatasource
id="ObjectDataSource1"
runat="server"
typename="Samples.AspNet.VB.EmployeeLogic"
selectmethod="GetAllEmployeesAsDataSet"
enablecaching="True"
cacheduration="30"
cacheexpirationpolicy="Absolute" />
</form>
</body>
</html>
В следующем примере кода показано, как реализовать метод-оболочку, который возвращает DataSet объект, чтобы включить кэширование с помощью ObjectDataSource элемента управления.The following code example demonstrates how to implement a wrapper method that returns a DataSet object to enable caching with an ObjectDataSource control. В базовой реализации EmployeeLogic
класса GetAllEmployees
метод возвращает ArrayList объект.In the base implementation of the EmployeeLogic
class, the GetAllEmployees
method returns an ArrayList object. Вместо рефакторинга объекта для работы ObjectDataSource на странице веб-форм добавляется метод оболочки с именем GetAllEmployeesAsDataSet
, возвращающий набор NorthwindEmployee
данных в виде DataSet .Instead of refactoring the object completely to work with the ObjectDataSource on a Web Forms page, a wrapper method named GetAllEmployeesAsDataSet
is added that returns a set of NorthwindEmployee
data as a DataSet.
Этот пример кода является частью большого примера, приведенного для ObjectDataSource класса.This code example is part of a larger example provided for the ObjectDataSource class.
//
// To support basic filtering, the employees cannot
// be returned as an array of objects, rather as a
// DataSet of the raw data values.
public static DataSet GetAllEmployeesAsDataSet () {
ICollection employees = GetAllEmployees();
DataSet ds = new DataSet("Table");
// Create the schema of the DataTable.
DataTable dt = new DataTable();
DataColumn dc;
dc = new DataColumn("FirstName", typeof(string)); dt.Columns.Add(dc);
dc = new DataColumn("LastName", typeof(string)); dt.Columns.Add(dc);
dc = new DataColumn("Title", typeof(string)); dt.Columns.Add(dc);
dc = new DataColumn("Courtesy", typeof(string)); dt.Columns.Add(dc);
dc = new DataColumn("Supervisor",typeof(Int32)); dt.Columns.Add(dc);
// Add rows to the DataTable.
IEnumerator emplEnum = employees.GetEnumerator();
DataRow row;
NorthwindEmployee ne;
while (emplEnum.MoveNext()) {
ne = emplEnum.Current as NorthwindEmployee;
row = dt.NewRow();
row["FirstName"] = ne.FirstName;
row["LastName"] = ne.LastName;
row["Title"] = ne.Title;
row["Courtesy"] = ne.Courtesy;
row["Supervisor"] = ne.Supervisor;
dt.Rows.Add(row);
}
// Add the complete DataTable to the DataSet.
ds.Tables.Add(dt);
return ds;
}
' To support basic filtering, the employees cannot
' be returned as an array of objects, rather as a
' DataSet of the raw data values.
Public Shared Function GetAllEmployeesAsDataSet() As DataSet
Dim employees As ICollection = GetAllEmployees()
Dim ds As New DataSet("Table")
' Create the schema of the DataTable.
Dim dt As New DataTable()
Dim dc As DataColumn
dc = New DataColumn("FirstName", GetType(String))
dt.Columns.Add(dc)
dc = New DataColumn("LastName", GetType(String))
dt.Columns.Add(dc)
dc = New DataColumn("Title", GetType(String))
dt.Columns.Add(dc)
dc = New DataColumn("Courtesy", GetType(String))
dt.Columns.Add(dc)
dc = New DataColumn("Supervisor", GetType(Int32))
dt.Columns.Add(dc)
' Add rows to the DataTable.
Dim emplEnum As IEnumerator = employees.GetEnumerator()
Dim row As DataRow
Dim ne As NorthwindEmployee
While emplEnum.MoveNext()
ne = CType(emplEnum.Current, NorthwindEmployee)
row = dt.NewRow()
row("FirstName") = ne.FirstName
row("LastName") = ne.LastName
row("Title") = ne.Title
row("Courtesy") = ne.Courtesy
row("Supervisor") = ne.Supervisor
dt.Rows.Add(row)
End While
' Add the complete DataTable to the DataSet.
ds.Tables.Add(dt)
Return ds
End Function 'GetAllEmployeesAsDataSet
Комментарии
ObjectDataSourceЭлемент управления поддерживает кэширование данных.The ObjectDataSource control supports data caching. При кэшировании данных вызовы Select метода извлекают данные из кэша, а не из бизнес-объекта, ObjectDataSource с которым работает.While data is cached, calls to the Select method retrieve data from the cache rather than from the business object that the ObjectDataSource works with. По истечении срока действия кэша Select метод получает данные из бизнес-объекта, а затем кэширует их снова.When the cache expires, the Select method retrieves data from the business object, and then caches the data again.
ObjectDataSourceЭлемент управления автоматически кэширует данные EnableCaching , когда свойству присвоено true
значение, а CacheDuration свойству присвоено больше 0, что указывает количество секунд, в течение которых кэш хранит данные, прежде чем запись кэша будет удалена.The ObjectDataSource control automatically caches data when the EnableCaching property is set to true
and the CacheDuration property is set to a value greater than 0, which indicates the number of seconds that the cache stores data before the cache entry is discarded. Значение 0 указывает на бесконечную длину кэша.A value of 0 indicates an infinitely long cache.
Кэш регулируется сочетанием длительности и CacheExpirationPolicy параметра.The cache is regulated by a combination of the duration and the CacheExpirationPolicy setting. Если CacheExpirationPolicy свойству присвоено Absolute значение, то ObjectDataSource кэширует данные при первом вызове Select метода и сохраняет его в памяти для, в большинстве случаев, в течение времени, заданного CacheDuration свойством.If the CacheExpirationPolicy property is set to the Absolute value, the ObjectDataSource caches data on the first call to the Select method and holds it in memory for, at most, the amount of time that is specified by the CacheDuration property. Данные могут быть освобождены до истечения времени, если требуется память.The data might be released before the duration time, if the memory is needed. Затем кэш обновляется во время следующего вызова Select метода.The cache is then refreshed during the next call to the Select method. Если CacheExpirationPolicy свойство имеет Sliding значение value, то элемент управления источника данных кэширует данные при первом вызове Select метода, но сбрасывает временное окно, для которого он удерживает кэш, при каждом последующем вызове Select метода.If the CacheExpirationPolicy property is set to Sliding value, the data source control caches data on the first call to the Select method, but resets the time window for which it holds the cache on each subsequent call to the Select method. Срок действия кэша истекает, если нет активности за время, равное CacheDuration свойству с момента последнего вызова Select метода.The cache expires if there is no activity for a time that is equal to the CacheDuration property since the last call to the Select method.
Применяется к
См. также раздел
- CacheExpirationPolicy
- EnableCaching
- Элементы управления веб-сервером с источником данныхData Source Web Server Controls
- Общие сведения об элементе управления ObjectDataSourceObjectDataSource Control Overview
- Создание исходного объекта элемента управления ObjectDataSourceCreating an ObjectDataSource Control Source Object