ASP.NET 缓存,十七--检索缓存项的值

Cache 中检索数据很简单,只需指定表示数据的键和值。然后,编写代码以在页上显示该数据。

检索缓存项的值

  • 以下代码创建一个 SourceDataView 对象,尝试检索分配了键 MyData1 的缓存数据,并将该数据分配给 Source。然后,确认该数据是否仍存储在 Cache 中,并将 Source 作为 DataGrid Web 服务器控件 MyDataGridDataSource 属性分配。最后,将该数据绑定到 MyDataGrid
    [C#]
        DataView Source;
        Source = (DataView)Cache["MyData1"];
        if(Source != null ) {
        MyDataGrid.DataSource = Source;
        MyDataGrid.DataBind();
        }
        [Visual Basic]
        Dim Source As DataView
        Source = CType(Cache("MyData1"), DataView)
        If Not (Source Is Nothing) Then
        MyDataGrid.DataSource = Source
        MyDataGrid.DataBind()
        End If 

检查某项是否存在于缓存中

  • 一个更复杂的情况是当数据源或数据集不在 Cache 中时,应用程序如何响应。下面的示例修改上一个过程中的代码以检查缓存的数据是否存在。如果它不在缓存中,则该示例重新创建它并将其添加到 Cache 中。
    [C#]
        DataView Source = (DataView)Cache["MyData1"];
        if (Source == null) {
        SqlConnection myConnection = new SqlConnection("server=localhost;Integrated Security=SSPI;database=pubs");
        SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors", myConnection);
        DataSet ds = new DataSet();
        myCommand.Fill(ds, "Authors");
        Source = new DataView(ds.Tables["Authors"]);
        Cache["MyData1"] = Source;
        }
        MyDataGrid.DataSource=Source;
        MyDataGrid.DataBind();
        [Visual Basic]
        Dim Source As DataView = CType(Cache("MyData1"), DataView)
        If Source Is Nothing Then
        Dim myConnection As New SqlConnection("server=localhost;Integrated Security=SSPI;database=pubs")
        Dim myCommand As New SqlDataAdapter("select * from Authors", myConnection)
        Dim ds As New DataSet()
        myCommand.Fill(ds, "Authors")
        Source = New DataView(ds.Tables("Authors"))
        Cache("MyData1") = Source
        End If
        MyDataGrid.DataSource = Source
        MyDataGrid.DataBind()