gpt4 book ai didi

c# - CompiledQuery.Compile 需要锁(EF4、SQL Server、C#)

转载 作者:太空宇宙 更新时间:2023-11-03 11:36:05 26 4
gpt4 key购买 nike

我有以下代码,我想知道是否需要锁:

private static Func _GetAccountAttributeGroup;

public static AccountAttributeGroup GetAccountAttributeGroup(this AcbsContainer objectContext, long? 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);
}

最佳答案

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

如果工作很少(即少于编译),我可能会使用局部变量来完成工作,然后使用 Interlocked.CompareExchange 来分配(当且仅当)字段仍然为空时。这意味着所有线程都获得相同的值,但可能意味着重复的工作(除第一个外的所有线程都被丢弃)。

如果可能出现这种情况,我实际上会使用静态字段初始值设定项,因为它的运行时开销较小;那么就不需要锁了。

关于c# - CompiledQuery.Compile 需要锁(EF4、SQL Server、C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6272573/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com