如何通过缓存键锁定?

Ami*_*mir 14 c# asp.net caching locking thread-safety

我试图实现一个通用的线程安全的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

}
Run Code Online (Sandbox Code Playgroud)

Ari*_*tos 5

第一个答案

在这种情况下,您使用互斥锁
Mutex可以使用Key进行锁定以基于该Key进行锁定-但您不能更改同一资源!

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();
    }   
}
Run Code Online (Sandbox Code Playgroud)

什么样的锁

我们有两种情况的锁。

1)一种情况是,我们在所有池,所有线程中使用公共资源。公用资源可以是文件,也可以是数据库本身。

在公共资源中,我们需要使用互斥锁

2)第二种情况是当我们使用仅对池内部可见的变量时-不同的池看不到该资源。例如静态List <>,静态Dictionary等。此静态变量,数组只能在池中访问,并且在不同池中它们是不同的。

在第二种情况下,lock()是最简单,最常见的使用方式。

比锁快

现在,当我们有一个静态字典并保存了很长时间,并且在那里进行过多的读/写操作时,一种更快的方法是避免整个程序等待, ReaderWriterLockSlim

您可以从这里举一个完整的例子: ReaderWriterLockSlim

使用ReaderWriterLockSlim,我们可以在不需要锁时避免它们-并且在读取时不需要锁定静态值-仅当在它们上写入时才可以。因此,对于静态值,我们可以建议将其用作缓存。

什么是asp.net中的池。

好像运行的不同程序相互隔离,但可以满足用户的传入请求。每个池都有自己的世界,彼此之间不沟通。每个池都有其初始化,静态值和寿命。为了在池之间拥有一些公共资源,您需要其他一些第三程序,例如数据库,磁盘上的文件,服务。

因此,如果您有多个池(网络花园)要同步它们以共享公共资源,则需要互斥锁。要在内部同步它们,请使用锁。

IIS应用程序池,辅助进程,应用程序域
ASP.NET的生存期静态变量