ThreadSafeCache.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. // Define JsonKit_NO_DYNAMIC to disable Expando support
  15. // Define JsonKit_NO_EMIT to disable Reflection.Emit
  16. // Define JsonKit_NO_DATACONTRACT to disable support for [DataContract]/[DataMember]
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Threading;
  20. namespace Topten.JsonKit
  21. {
  22. public class ThreadSafeCache<TKey, TValue>
  23. {
  24. public ThreadSafeCache()
  25. {
  26. }
  27. public TValue Get(TKey key, Func<TValue> createIt)
  28. {
  29. // Check if already exists
  30. _lock.EnterReadLock();
  31. try
  32. {
  33. TValue val;
  34. if (_map.TryGetValue(key, out val))
  35. return val;
  36. }
  37. finally
  38. {
  39. _lock.ExitReadLock();
  40. }
  41. // Nope, take lock and try again
  42. _lock.EnterWriteLock();
  43. try
  44. {
  45. // Check again before creating it
  46. TValue val;
  47. if (!_map.TryGetValue(key, out val))
  48. {
  49. // Store the new one
  50. val = createIt();
  51. _map[key] = val;
  52. }
  53. return val;
  54. }
  55. finally
  56. {
  57. _lock.ExitWriteLock();
  58. }
  59. }
  60. public bool TryGetValue(TKey key, out TValue val)
  61. {
  62. _lock.EnterReadLock();
  63. try
  64. {
  65. return _map.TryGetValue(key, out val);
  66. }
  67. finally
  68. {
  69. _lock.ExitReadLock();
  70. }
  71. }
  72. public void Set(TKey key, TValue value)
  73. {
  74. _lock.EnterWriteLock();
  75. try
  76. {
  77. _map[key] = value;
  78. }
  79. finally
  80. {
  81. _lock.ExitWriteLock();
  82. }
  83. }
  84. Dictionary<TKey, TValue> _map = new Dictionary<TKey,TValue>();
  85. ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
  86. }
  87. }