Mutex抛出UnauthorizedAccessException

时间:2014-08-04 16:41:02

标签: c# multithreading mutex

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

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.

我发现一些帖子暗示这可能是由于竞争条件造成的。不幸的是,我的Mutex知识非常有限,我很难看出问题出在哪里。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

为什么不使用任何内置的.NET缓存?我没有在代码中看到.NET缓存实现无法处理的任何内容。另一种选择可能是readerwriterlockslim类,因为你真的只需要锁定写入。

相关问题