CompiledQuery.Compile需要锁定(EF4,SQL Server,C#)

时间:2011-06-07 23:03:06

标签: c# entity-framework sql-server-2008 linq-to-entities

我有以下代码,如果我需要锁定,我想知道:

  

private static Func   _GetAccountAttributeGroup;

     

public static AccountAttributeGroup   GetAccountAttributeGroup(此   AcbsContainer objectContext,好吗? id)的

    {
        if (id == null)
        {
            return null;
        }

        if (_GetAccountAttributeGroup == null)
        {
            _GetAccountAttributeGroup = CompiledQuery.Compile<AcbsContainer,
            long, AccountAttributeGroup>((ctx, key) =>
            ctx.AccountAttributeGroups.FirstOrDefault(e> => e.Id == key));
        }

        return _GetAccountAttributeGroup(objectContext, id.Value);
    }

1 个答案:

答案 0 :(得分:2)

我可能 通过仔细检查来做到这一点(即检查是否为null;如果为null,则锁定并且再次检查;如果仍然为null,则执行编译工作,分配)。但是,这主要是为了防止冷启动期间的重复工作。

如果工作是最小的(即低于编译),我可能会使用局部变量来完成工作,然后使用Interlocked.CompareExchange来指定if(并且仅当)字段仍然为null。这意味着所有线程都获得相同的值,但可能意味着重复工作(除了第一个之外的所有线程都被丢弃)。

如果可能出现问题,我实际上会使用静态字段初始化程序,因为它具有较少的运行时开销;那时不需要锁。