我有一个Web应用程序,需要利用应用程序缓存来存储数据(由于按请求一次次地获取数据的高开销)。请参见先前的帖子:https://stackoverflow.com/a/16961962/236860。
这种方法似乎很有效,但我在网站错误中偶尔看到以下错误:
这种方法似乎很有效,但我在网站错误中偶尔看到以下错误:
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)
作为参考,这是代码块:
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;
}
经过我的调研,显示此问题是由一个进程线程试图释放它未创建的互斥锁造成的,但我不明白这怎么会发生。
有人能否建议我如何重新构建代码以避免这个问题?