ThreadSafeCache.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // JsonKit v0.5 - A simple but flexible Json library in a single .cs file.
  2. //
  3. // Copyright (C) 2014 Topten Software (contact@toptensoftware.com) All rights reserved.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this product
  6. // except in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed under the
  11. // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  12. // either express or implied. See the License for the specific language governing permissions
  13. // and limitations under the License.
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Threading;
  17. namespace Topten.JsonKit
  18. {
  19. class ThreadSafeCache<TKey, TValue>
  20. {
  21. public ThreadSafeCache()
  22. {
  23. }
  24. public TValue Get(TKey key, Func<TValue> createIt)
  25. {
  26. // Check if already exists
  27. _lock.EnterReadLock();
  28. try
  29. {
  30. TValue val;
  31. if (_map.TryGetValue(key, out val))
  32. return val;
  33. }
  34. finally
  35. {
  36. _lock.ExitReadLock();
  37. }
  38. // Nope, take lock and try again
  39. _lock.EnterWriteLock();
  40. try
  41. {
  42. // Check again before creating it
  43. TValue val;
  44. if (!_map.TryGetValue(key, out val))
  45. {
  46. // Store the new one
  47. val = createIt();
  48. _map[key] = val;
  49. }
  50. return val;
  51. }
  52. finally
  53. {
  54. _lock.ExitWriteLock();
  55. }
  56. }
  57. public bool TryGetValue(TKey key, out TValue val)
  58. {
  59. _lock.EnterReadLock();
  60. try
  61. {
  62. return _map.TryGetValue(key, out val);
  63. }
  64. finally
  65. {
  66. _lock.ExitReadLock();
  67. }
  68. }
  69. public void Set(TKey key, TValue value)
  70. {
  71. _lock.EnterWriteLock();
  72. try
  73. {
  74. _map[key] = value;
  75. }
  76. finally
  77. {
  78. _lock.ExitWriteLock();
  79. }
  80. }
  81. Dictionary<TKey, TValue> _map = new Dictionary<TKey,TValue>();
  82. ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
  83. }
  84. }