下圖是WeakReference類別提供的簡單範例,建構子指向一個Target Object記憶體,當GC.Collect()後,該Target Object會變成null, 且IsAlive=False。然而若在GC前有讀取過該Target記憶體(第11行),第15行的結果卻是IsAlive=True。若整段Code貼到一個for loop視野內,Target存活的狀況又變得不一樣了,這些涉及到GC的回收機制(Generation)及適用策略而變得不可預測,所以官方文件裏都會告訴你WeakReference指向的Target記憶體存活狀況不可靠,儘量不要用。

然而有些資料不是那麼重要,而且也無法預知它的內容何時會被釋放,不如就用GC自由掃射,只要我們存取變數值時安全檢查一下就好。以下就是一個簡單的Cache Dictionary集合實作範例:
WeakReference項目GC回收的時機點很難預測,我們該怎麼安全地讀值呢?簡單地說,就是比對一下項目Target值 是否為null值就好,而異動集合項目時配合lock{}也可來達到ThreadSafe。
因為讀值需要判斷一堆的,所以新式的ASP.NET Caching內部實作時間Expire存活機制,讓集合的項目 能明確保存一段時間,這會是更好的管理方式。
1 comment:
Just 20 years ago, horse racing and the lottery were the only video games in town. But right now, you can to|you presumably can} drop $100 on the NFL playoffs, a Knicks or Nets game, or another sporting event in the world, 온라인 바카라 all with the contact of a telephone. Since voters permitted desk game casinos in New York in 2013, New York state approved seven licenses. Just 4 were issued to on line casino operators, all of them upstate. While the platform doesn’t have too many deposit methods out there, withdrawals are notably troublesome as there are only three of them.
Post a Comment