c# – 我如何用缓存键锁定?
发布时间:2020-12-15 03:46:03 所属栏目:百科 来源:网络整理
导读:我试图实现一个通用的线程安全的Cache方法,我想知道我应该如何实现它的锁. 它应该看起来像这样: //private static readonly lockObject = new Object();public T GetCacheT(string key,FuncT valueFactory...){ // try to pull from cache here lock (lockO
我试图实现一个通用的线程安全的Cache方法,我想知道我应该如何实现它的锁.
它应该看起来像这样: //private static readonly lockObject = new Object(); public T GetCache<T>(string key,Func<T> valueFactory...) { // try to pull from cache here 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. { // cache was empty before we got the lock,check again inside the lock // cache is still empty,so retreive the value here // store the value in the cache here } // return the cached value here } 有什么建议么? 解决方法
这是您使用
mutex的情况
public T GetCache<T>(string key,Func<T> valueFactory...) { // note here that I use the key as the name of the mutex // also here you need to check that the key have no invalid charater // to used as mutex name. var mut = new Mutex(true,key); try { // Wait until it is safe to enter. mut.WaitOne(); // here you create your cache } finally { // Release the Mutex. mut.ReleaseMutex(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读