c# – 我如何用缓存键锁定?

前端之家收集整理的这篇文章主要介绍了c# – 我如何用缓存键锁定?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图实现一个通用的线程安全的Cache方法,我想知道我应该如何实现它的锁.

它应该看起来像这样:

  1. //private static readonly lockObject = new Object();
  2.  
  3. public T GetCache<T>(string key,Func<T> valueFactory...)
  4. {
  5.  
  6. // try to pull from cache here
  7.  
  8. lock (lockObject) // I don't want to use static object lock here because then every time a lock is performed,all cached objects in my site have to wait,regarding of the cache key.
  9. {
  10. // cache was empty before we got the lock,check again inside the lock
  11.  
  12. // cache is still empty,so retreive the value here
  13.  
  14. // store the value in the cache here
  15. }
  16.  
  17. // return the cached value here
  18.  
  19. }

有什么建议么?
谢谢,
阿米尔.

解决方法

这是您使用 mutex的情况
  1. public T GetCache<T>(string key,Func<T> valueFactory...)
  2. {
  3. // note here that I use the key as the name of the mutex
  4. // also here you need to check that the key have no invalid charater
  5. // to used as mutex name.
  6. var mut = new Mutex(true,key);
  7.  
  8. try
  9. {
  10. // Wait until it is safe to enter.
  11. mut.WaitOne();
  12.  
  13. // here you create your cache
  14. }
  15. finally
  16. {
  17. // Release the Mutex.
  18. mut.ReleaseMutex();
  19. }
  20. }

猜你在找的C#相关文章