I have the following code for which I want t开发者_Go百科o know if I need a lock:
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); }
I probably would do that with double-check (I.e check if null; if null, lock and check again; if still null, do the work to compile and assign). However, this is mainly to prevent duplicated work during cold-start than anything else.
If the work was minimal (I.e. Less than compile) I might use a local variable to do the work, then use Interlocked.CompareExchange to assign if (and only if) the field is still null. This means all threads get the same value, but might mean duplicated effort (all but the first are discarded).
If the scenario in question is likely, I would actually use a static field initializer, as that has less runtime overhead; no locks are necessary then.
精彩评论