我有以下代码,如果我需要锁定,我想知道:
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); }
答案 0 :(得分:2)
我可能 通过仔细检查来做到这一点(即检查是否为null;如果为null,则锁定并且再次检查;如果仍然为null,则执行编译工作,分配)。但是,这主要是为了防止冷启动期间的重复工作。
如果工作是最小的(即低于编译),我可能会使用局部变量来完成工作,然后使用Interlocked.CompareExchange来指定if(并且仅当)字段仍然为null。这意味着所有线程都获得相同的值,但可能意味着重复工作(除了第一个之外的所有线程都被丢弃)。
如果可能出现问题,我实际上会使用静态字段初始化程序,因为它具有较少的运行时开销;那时不需要锁。