comparison Cache.cs @ 0:3ab940a0c7a0

Initial commit
author Ivo Smits <Ivo@UCIS.nl>
date Tue, 11 Sep 2012 16:28:53 +0200
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:3ab940a0c7a0
1 using System;
2 using System.Collections.Generic;
3
4 namespace UCIS {
5 public class Cache<TKey, TValue> {
6 private Dictionary<TKey, WeakReference> _items;
7
8 public Cache() {
9 _items = new Dictionary<TKey, WeakReference>();
10 }
11
12 public int Count { get { return _items.Count; } }
13 public int getCount(bool checkAlive) {
14 Purge();
15 return _items.Count;
16 }
17
18 private void getItem(TKey key, out TValue value, out bool exists, out bool collected) {
19 WeakReference w;
20 lock (_items) {
21 if (!_items.TryGetValue(key, out w)) {
22 value = default(TValue);
23 exists = false;
24 collected = false;
25 return;
26 }
27 Object r = w.Target;
28 if (r == null) {
29 _items.Remove(key);
30 value = default(TValue);
31 exists = false;
32 collected = true;
33 return;
34 }
35 value = (TValue)r;
36 exists = true;
37 collected = false;
38 return;
39 }
40 }
41
42 public bool TryGetValue(TKey key, out TValue value) {
43 bool exists, collected;
44 getItem(key, out value, out exists, out collected);
45 return exists;
46 }
47
48 public void Purge() {
49 lock (_items) {
50 List<TKey> remove = new List<TKey>();
51 foreach (KeyValuePair<TKey, WeakReference> kvp in _items) {
52 if (!kvp.Value.IsAlive) remove.Add(kvp.Key);
53 }
54 foreach (TKey key in remove) {
55 _items.Remove(key);
56 }
57 }
58 }
59
60 public void Add(TKey key, TValue value) {
61 lock(_items) _items.Add(key, new WeakReference(value));
62 }
63
64 public bool Remove(TKey key) {
65 lock(_items) return _items.Remove(key);
66 }
67
68 public void Clear() {
69 _items.Clear();
70 }
71 }
72 }