相关疑难解决方法(0)

为什么锁(这个){...}不好?

MSDN文档说,

public class SomeObject
{
  public void SomeOperation()
  {
    lock(this)
    {
      //Access instance variables
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果可以公开访问实例,那就是"一个问题".我想知道为什么?是因为锁定的持有时间超过了必要的时间吗?还是有一些更阴险的原因?

c# multithreading locking

462
推荐指数
6
解决办法
15万
查看次数

HttpRuntime.Cache最佳实践

在过去,我已经锁定了访问HttpRuntime.Cache机制.我不确定我过去是否真的研究过这个问题,盲人用锁把它围起来.

你觉得这真的有必要吗?

c# httpruntime.cache

20
推荐指数
2
解决办法
2万
查看次数

如何通过方法参数锁定?

string Get(string key){
   lock(_sync){
    //   DoSomething
   }
}
Run Code Online (Sandbox Code Playgroud)

如果DoSomething仅依赖于密钥,我想要密钥依赖锁.我认为它可能是带有同步对象的字典.有没有完整的解决方案?

像真实例子一样 在asp.net中锁定缓存的最佳方法是什么?

c# multithreading locking

11
推荐指数
1
解决办法
2127
查看次数

间歇性Linq FirstOrDefault错误 - 索引超出了数组的范围

大约每月一次,我们遇到了一个奇怪的错误,我没有解释.错误是这样的:

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)

c# linq asp.net thread-safety asp.net-caching

5
推荐指数
1
解决办法
718
查看次数

ASP.NET lock()不起作用

我试图锁定一个静态字符串对象来访问缓存,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()永远不会执行.

asp.net caching locking

1
推荐指数
1
解决办法
3604
查看次数