在MSDN文档说,
public class SomeObject
{
public void SomeOperation()
{
lock(this)
{
//Access instance variables
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果可以公开访问实例,那就是"一个问题".我想知道为什么?是因为锁定的持有时间超过了必要的时间吗?还是有一些更阴险的原因?
在过去,我已经锁定了访问HttpRuntime.Cache机制.我不确定我过去是否真的研究过这个问题,盲人用锁把它围起来.
你觉得这真的有必要吗?
string Get(string key){
lock(_sync){
// DoSomething
}
}
Run Code Online (Sandbox Code Playgroud)
如果DoSomething仅依赖于密钥,我想要密钥依赖锁.我认为它可能是带有同步对象的字典.有没有完整的解决方案?
像真实例子一样 在asp.net中锁定缓存的最佳方法是什么?
大约每月一次,我们遇到了一个奇怪的错误,我没有解释.错误是这样的:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Collections.Generic.List`1.Enumerator.MoveNext() at
System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
Run Code Online (Sandbox Code Playgroud)
这是发生错误的代码.在MyObject的构造函数中调用此方法:
// pull a list of MyObjects from the cache so we can see if this one exists
List<MyObject> MyObjectList= System.Web.HttpRuntime.Cache["MyObjects"] as List<MyObject>;
if (MyObjectList!= null)
{
// this is where the error happens. Just getting an object out based on its id
MyObject obj = MyObjectList.FirstOrDefault(m => m.Id == this.Id);
if(obj != null){
// great, it already exists in the cache
} …Run Code Online (Sandbox Code Playgroud) 我试图锁定一个静态字符串对象来访问缓存,lock()块在我的本地执行,但每当我将它部署到服务器时,它就永远锁定.我将每一步写入事件日志以查看进程并且锁定(对象)只会导致服务器上的死锁.lock()之后的命令永远不会执行,因为我在事件日志中看不到条目.以下是代码:
public static string CacheSyncObject = "CacheSync";
public static DataView GetUsers()
{
DataTable dtUsers = null;
if (HttpContext.Current.Cache["dtUsers"] != null)
{
Global.eventLogger.Write(String.Format("GetUsers() cache hit: {0}",dtUsers.Rows.Count));
return (HttpContext.Current.Cache["dtUsers"] as DataTable).Copy().DefaultView;
}
Global.eventLogger.Write("GetUsers() cache miss");
lock (CacheSyncObject)
{
Global.eventLogger.Write("GetUsers() locked SyncObject");
if (HttpContext.Current.Cache["dtUsers"] != null)
{
Global.eventLogger.Write("GetUsers() opps, another thread filled the cache, release lock");
return (HttpContext.Current.Cache["dtUsers"] as DataTable).Copy().DefaultView;
}
Run Code Online (Sandbox Code Playgroud)
Global.eventLogger.Write("GetUsers()锁定SyncObject"); ==>这永远不会写入日志,这对我来说意味着,lock()永远不会执行.