互斥抛出UnauthorizedAccessException

本文关键字:UnauthorizedAccessException | 更新日期: 2023-09-27 18:16:23

我正在尝试编写一个用于压缩和缓存web脚本的自定义机制。我使用互斥锁来为缓存创建方法提供托管访问。

public class HttpApplicationCacheManager
{
  public object Get(
     Cache cache,   // Reference to the HttpContext.Cache
     string key,    // Id of the cached object
     int retrievalWaitTime,
     Func<object> getData,  // Method that builds the string to be cached
     Func<CacheDependency> getDependency)  // CacheDependency object for the 
                                           // string[] of file paths to be cached
  {
     Mutex mutex = null;
     bool iOwnMutex = false;
     object data = cache[key];
     // Start check to see if available on cache
     if (data == null)
     {
        try
        {
           // Lock base on resource key
           // (note that not all chars are valid for name)
           mutex = new Mutex(false, key);
           // Wait until it is safe to enter (someone else might already be
           // doing this), but also add 30 seconds max.
           iOwnMutex = mutex.WaitOne(retrievalWaitTime * 1000);
           // Now let's see if some one else has added it...
           data = cache[key];
           // They did, so send it...
           if (data != null)
           {
              return data;
           }
           // Still not there, so now is the time to look for it!
           data = getData();
           var dependency = getDependency();
           cache.Insert(key, data, dependency);
        }
        catch
        {
           throw;
        }
        finally
        {
           // Release the Mutex.
           if ((mutex != null) && (iOwnMutex))
           {
              mutex.ReleaseMutex();
           }
        }
     }
     return data;
  }
}

虽然这工作,我偶尔看到以下错误:

System.UnauthorizedAccessException 
   Access to the path 'SquashCss-theme.midnight.dialog' is denied.

我发现一些帖子暗示这可能是由于竞争条件。不幸的是,我的互斥锁知识非常有限,我正在努力找出问题可能出在哪里。

互斥抛出UnauthorizedAccessException

为什么不直接使用内建的。net缓存呢?我在你的代码中没有看到任何不能被。net缓存实现处理的东西。另一个选项可能是readerwriterlockslim类,因为您实际上只需要锁定写。

相关文章:
  • 没有找到相关文章