Reputation: 259
We are setting session-timeout for 1 hour:
<system.web>
<sessionState mode="InProc" timeout="60"/>
</system.web>
It works as expected.
Alongwith "Session", we create user specific data-cache to reuse the data.
We use unique cache-key for each logged in user:
var studentId = GetStudentIdFromRequest();
var cacheKey = "SyllabusInfoCacheKey_" + studentId;
We set the expiration time of cache as:
Cache.Insert("MyKey", myObject, null, DateTime.Today.AddDays(1), TimeSpan.Zero);
But I need to remove the user specific data-cache once the session gets timeout.
Kindly help me out.
Upvotes: 0
Views: 787
Reputation: 303
Please try below.
Put below code in Global.asax file in your project.
Shared Dict As New Dictionary(Of String, String)
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application startup
Application.Add("AllSession", Dict)
End Sub
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a session ends.
' Note: The Session_End event is raised only when the sessionstate mode
' is set to InProc in the Web.config file. If session mode is set to StateServer
' or SQLServer, the event is not raised.
If Dict.ContainsKey(Me.Session.SessionID) Then
HttpRuntime.Cache.Remove(Dict.Item(Me.Session.SessionID))
Dict.Remove(Me.Session.SessionID)
Application.Add("AllSession", Dict)
End If
End Sub
Please put this code in you vb file where you are assigning session.
Dim cacheKey As New Random
Dim DictcacheKey As Dictionary(Of String, String)
DictcacheKey = Application("AllSession")
If Not DictcacheKey.ContainsKey(HttpContext.Current.Session.SessionID) Then
DictcacheKey.Add(HttpContext.Current.Session.SessionID, cacheKey.Next())
Application.Add("AllSession", DictcacheKey)
Cache.Insert(cacheKey.Next(), DictcacheKey, Nothing, DateTime.Today.AddDays(1), TimeSpan.Zero)
End If
Note: convert this code in C# if you are not using vb.
Upvotes: 1
Reputation: 2202
If you want the data in cache to be in sync with the session, i would suggest to change the approach i.e to store the data in session itself instead of cache. Your requirement will be automatically taken care of.
PS: In your previous question i had suggested the Cache approach, since you wanted to use Cache instead of Session. But it looks like the use case, suits best for Session usage instead of Cache. Please comment if you see any issue with the Session approach.
Upvotes: 1