我之前使用應用程序對象來緩存永不改變的數據。我正在重寫這個項目,並且發現應用程序對象是一個禁止對象,並且只是爲了支持來自ASP的傳統支持。散列表中的asp.net靜態緩存
我知道我也可以使用緩存 - 但我不想因爲我使用那些需要失效的數據。
因此,我正在尋找靜態數據的靜態變量(有意義)。
我的問題是,我沒有在每個類中指定靜態變量,而是考慮使用散列表來存儲所有數據並將其包裝到自己的類中 - 就像工廠一樣。
事情是這樣的:
''' <summary>
''' Methods and properties related to the access and management of the local static memory cache.
''' Fastest type of cache but not available across applications, web farm or web garden environments.
''' Use this cache when data is static or can be stale across application instances.
''' </summary>
''' <remarks></remarks>
Public Class LocalStaticCache
'Internal data holder:
Private Shared _objCache As Hashtable = Hashtable.Synchronized(New Hashtable)
Private Sub New()
End Sub
''' <summary>
''' Gets or sets an object in cache. Returns Nothing if the object does not exist.
''' </summary>
''' <param name="key">The name of the object.</param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Property Item(key As String) As Object
Get
If String.IsNullOrEmpty(key) Then Return Nothing
Return _objCache(key)
End Get
Private Set(value As Object)
_objCache(key) = value
End Set
End Property
''' <summary>
''' Insert an object into the cache.
''' </summary>
''' <param name="key">The unique object key.</param>
''' <param name="value">The object to store in the cache.</param>
''' <remarks></remarks>
Public Shared Sub Insert(key As String,
value As Object)
If Not String.IsNullOrWhiteSpace(key) Then
If _objCache.ContainsKey(key) Then
'If the key already exists in the Cache it will overwrite only if the objects differ:
Interlocked.CompareExchange(Item(key), value, value)
Return
End If
'store the item to the cache:
Item(key) = value
End If
End Sub
''' <summary>
''' Remove an object from the cache.
''' </summary>
''' <param name="key">The key of the object to remove.</param>
''' <remarks></remarks>
Public Shared Sub Remove(key As String)
If _objCache.ContainsKey(key) Then
_objCache.Remove(key)
End If
End Sub
End Class
你想存儲所有靜態數據裝入一個哈希表,這是對性能, 一個好主意,或者這將是更好地爲每個類有內部自身的靜態數據持有者他們的課?
此線程是否安全?注意:我正在實施Hashtable.Synchronized和Interlocked.CompareExchange以防止競爭條件 - 但鎖定和爭用怎麼辦??
請注意,數據在第一次設置後永遠不會更改(哈希表中的項目永遠不需要更新)。
我有數據集和大塊的記錄集作爲內存流來存儲。
任何想法或指針?
謝謝。
嗯,asp.net有它自己的緩存設施,爲什麼不使用它們?看看這個 - http://msdn.microsoft.com/en-us/library/6hbbsfk6.aspx –
或者如果你不想參考asp.net http://msdn.microsoft.com/en-us/library /dd997357.aspx –
你存儲什麼「數據」?如果它是相同類型,我會建議使用類型安全字典。在任何地方鑄造對象的需求也是將這些靜態對象封裝在它們所屬的類中的強類型的一個很好的理由。這使得代碼更易讀,並且可以更好地記錄對象的用途。但是一般使用靜態對象的方法對於使用量大而且從不改變的數據來說是好的,儘管我更喜歡Cache。 –