Why does the lock object have to be static?

前端 未结 3 1878
别那么骄傲
别那么骄傲 2020-11-28 02:33

It is very common to use a private static readonly object for locking in multi threading. I understand that private reduces the entry points to the locking object by tighten

相关标签:
3条回答
  • 2020-11-28 03:05

    It isn't "very common to use a private static readonly object for locking in multi threading" - rather, it is common to use a lock at the appropriate / chosen granularity. Sometimes that is static. More often, IMO, it isn't - but is instance based.

    The main time you see a static lock is for a global cache, or for deferred loading of global data / singletons. And in the latter, there are better ways of doing it anyway.

    So it really depends: how is Locker used in your scenario? Is it protecting something that is itself static? If so, the lock should be static. If it is protecting something that is instance based, then IMO the lock should also be instance based.

    0 讨论(0)
  • 2020-11-28 03:06

    The scope and lifetime of a lock can/should depend on the 'thing' you want to lock. Static locks are mostly used to lock static things.

    0 讨论(0)
  • 2020-11-28 03:19

    It doesn't have to be static, in fact sometimes it should not be static.

    The variable should live in the same scope as the methods where you use it for locking. If the methods are static, the variable should be static, and if the methods are instance methods, the variable should be an instance varible.

    A static variable will still work when used to lock in an instance method, but then you will be locking too much. You will lock all methods in all instances, not just the methods in the same instance.

    0 讨论(0)
提交回复
热议问题