我们有下面的代码用于提高性能。它工作正常,但每隔几天我们就会开始收到大量异常(如下)。它与音量无关,但它是随机的。
注释:/// 执行锁定代码以在必要时产生结果,同时线程锁定它,然后缓存结果。
第 45 行是:lock (_keys.First(k => k == key))
有任何想法吗?
代码:
public class LockedCaching
{
private static List<string> _keys = new List<string>();
public class Result
{
public object Value { get; set; }
public bool ExecutedDataOperation { get; set; }
}
/// <summary>
/// Performs the locked code to produce the result if necessary while thread locking it and then caching the result.
/// </summary>
/// <param name="key"></param>
/// <param name="expiration"></param>
/// <param name="data"></param>
/// <returns></returns>
public static Result Request(string key, DateTime expiration, RequestDataOperation data)
{
if (key == null)
{
return new Result { Value = data(), ExecutedDataOperation = true };
}
//Does the key have an instance for locking yet (in our _keys list)?
bool addedKey = false;
bool executedDataOperation = false;
if (!_keys.Exists(s => s == key))
{
_keys.Add(key);
addedKey = true;
}
object ret = HttpContext.Current.Cache[key];
if (ret == null)
{
lock (_keys.First(k => k == key))
{
ret = HttpContext.Current.Cache[key];
if (ret == null)
{
ret = data();
executedDataOperation = true;
if(ret != null)
HttpContext.Current.Cache.Insert(key, ret, null, expiration, new TimeSpan(0));
}
}
}
if (addedKey)
CleanUpOldKeys();
return new Result { Value = ret, ExecutedDataOperation = executedDataOperation };
}
private static void CleanUpOldKeys()
{
_keys.RemoveAll(k => HttpContext.Current.Cache[k] == null);
}
}
例外:
异常:System.Web.HttpUnhandledException (0x80004005):引发了“System.Web.HttpUnhandledException”类型的异常。---> System.ArgumentNullException:值不能为空。参数名称:System.Web.Caching.CacheInternal.DoGet(Boolean isPublic, String key, CacheGetOptions getOptions) 中 PROJECT\LockedCaching.cs 中 PROJECT.LockedCaching.b__8(String k) 的键:System.Collections.Generic 的第 64 行。列表
1.RemoveAll(Predicate
1 个匹配项)在 PROJECT\LockedCaching.cs 中的 PROJECT.LockedCaching.CleanUpOldKeys():PROJECTLockedCaching.Request(String key, DateTime expiration, RequestDataOperation data) 中 PROJECT\LockedCaching.cs 中的第 64 行:FeaturesWithFlags1.DataBind() 中的第 58 行System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Control.LoadRecursive() at System.Web .UI.Control.LoadRecursive() 在 System.Web.UI.Control.LoadRecursive() 在 System.Web.UI.Control.LoadRecursive() 在 System.Web.UI.Control.LoadRecursive() 在 System.Web.UI .Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) 在 System.Web.UI.Page.HandleError(Exception e) 在 System.Web.UI.Page。ProcessRequestMain(布尔 includeStagesBeforeAsyncPoint,布尔 includeStagesAfterAsyncPoint)在 System.Web.UI.Page.ProcessRequest(布尔 includeStagesBeforeAsyncPoint,布尔 includeStagesAfterAsyncPoint)在 System.Web.UI.Page.ProcessRequest()在 System.Web.UI.Page.ProcessRequest(HttpContext 上下文) 在 System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() 在 System.Web.HttpApplication.ExecuteStep(IExecutionStep 步骤,布尔&完成同步)System.Web.HttpApplication.IExecutionStep.Execute() 在 System.Web.HttpApplication.ExecuteStep(IExecutionStep 步骤,布尔值&完成同步)System.Web.HttpApplication.IExecutionStep.Execute() 在 System.Web.HttpApplication.ExecuteStep(IExecutionStep 步骤,布尔值&完成同步)
使用它的 Web 控件 - 此 Web 控件从 Web 服务请求位置列表。我们几乎在任何我们调用 web 服务的地方都使用这个lockedcache 请求:
public override void DataBind()
{
try
{
string cacheKey = "GetSites|";
mt_site_config[] sites = (mt_site_config[])LockedCaching.Request(cacheKey, DateTime.UtcNow.AddMinutes(10),
() =>
{
WebServiceClient service = new WebServiceClient();
sites = service.GetSites();
service.Close();
return sites;
}).Value;
ddlLocation.Items.Clear();
ddlLocation.Items.Add(new ListItem("Please Select"));
ddlLocation.Items.Add(new ListItem("Administration"));
ddlLocation.Items.AddRange
(
sites.Select
(
s => new ListItem(s.site_name + " " + s.site_location, s.th_code.ToString())
).ToArray()
);
}
catch (Exception ex) {
Logger.Error("ContactUs Control Exception: Exp" + Environment.NewLine + ex.Message);
}
base.DataBind();
}
谢谢您的意见。ConcurrentDictionary 是要走的路。我们收到错误的原因是因为 linq 代码“lock (_keys.First(k => k == key))”返回异常而不是 null。使用并发字典会更安全,并且希望不会导致任何锁定问题。
修改代码:
public class LockedCaching
{
public class Result
{
public object Value { get; set; }
public bool ExecutedDataOperation { get; set; }
}
public static Result Request(string key, DateTime expiration, RequestDataOperation data)
{
if (key == null)
{
return new Result { Value = data(), ExecutedDataOperation = true };
}
object results = HttpContext.Current.Cache[key];
bool executedDataOperation = false;
if (results == null)
{
object miniLock = _miniLocks.GetOrAdd(key, k => new object());
lock (miniLock)
{
results = HttpContext.Current.Cache[key];
if (results == null)
{
results = data();
executedDataOperation = true;
if (results != null)
HttpContext.Current.Cache.Insert(key, results, null, expiration, new TimeSpan(0));
object temp;
object tempResults;
if (_miniLocks.TryGetValue(key, out temp) && (temp == miniLock))
_miniLocks.TryRemove(key, out tempResults);
}
}
}
return new Result { Value = results, ExecutedDataOperation = executedDataOperation };
}
private static readonly ConcurrentDictionary<string, object> _miniLocks =
new ConcurrentDictionary<string, object>();
}