首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >释放互斥锁

释放互斥锁
EN

Stack Overflow用户
提问于 2013-06-13 00:24:55
回答 1查看 10.6K关注 0票数 8

我有一个web应用程序,它需要利用应用程序缓存来存储数据(由于在逐个请求的基础上获取数据的高开销)。请参阅https://stackoverflow.com/a/16961962/236860上的前一篇文章

这种方法似乎工作得很好,但我在网站的错误中看到了以下偶尔的错误:

代码语言:javascript
复制
System.ApplicationException: Object synchronization method was called from an
unsynchronized block of code.
at System.Threading.Mutex.ReleaseMutex()
at InboxInsight.Web.Web_Controls.Twitter.TwitterFeed.GetTwitterData(HttpContext context)
at InboxInsight.Web.Web_Controls.Twitter.TwitterFeed.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

作为参考,下面是代码块:

代码语言:javascript
复制
public string GetData(HttpContext context)
{
    var cache      = context.Cache;
    Mutex mutex    = null;
    string data    = (string)cache[CacheKey];

    // 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(true, CacheKey);

           // Wait until it is safe to enter (someone else might already be
           // doing this), but also add 30 seconds max.
           mutex.WaitOne(30000);

           // Now let's see if some one else has added it...
           data = (string)cache[CacheKey];

           // They did, so send it...
           if (data != null)
           {
              return data;
           }


           // Still not there, so now is the time to look for it!
           data = GetSlowFeed(context);

           cache.Remove(CacheKey);
           cache.Add(CacheKey, data, null, GetExpiryDate(),
              TimeSpan.Zero, CacheItemPriority.Normal, null);
       }
       finally
       {
           // Release the Mutex.
           if (mutex != null)
           {
              mutex.ReleaseMutex();
           }
       }
    }

    return data;
}

从我的研究来看,它表明这个问题是由一个进程线程试图释放它没有创建的Mutex引起的,但我不明白这是怎么发生的。

有没有人能建议我如何重新组织代码以避免这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-06-13 00:36:44

您没有处理mutex.WaitOne返回false的情况,即超时。如果WaitOne返回false,那么您不拥有互斥锁,因此不需要释放它。

代码语言:javascript
复制
bool iOwnTheMutex;

try {
    // set up mutex here...
    iOwnTheMutex = mutex.WaitOne(2000);
    if (iOwnTheMutex) {
       // do what you need to do
    }
}
finally {
    if (mutex != null && iOwnTheMutex) {
       mutex.ReleaseMutex();
    }
}    
票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17070583

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档