ShuberFu
ShuberFu

Reputation: 709

Does C# lock object require lazy initialization

I may be missing some blindingly obvious documentation somewhere, but is static readonly member variable guaranteed to be initialized properly for use as a lock object?

In short, I have a library class that performs operation on an external resource that should only have a single instance touching it at any one time (don't have to worry about another process, it's only on a single process). The library class itself can have multiple instances in multiple threads, so in order to ensure that only one instance access said resource at a time, I need to use a lock.

I've seen a lot of lock object declaration like this.

private static readonly object _lockObj = new object();

Can this guarantee that multiple threads won't, by bad timing, initialize the two objects at the same time and lock on two objects? Or should I be creating the lock object like this.

private static readonly Lazy<object> _lockObj = new Lazy<object>(() => new object());

P.S. I'm referring to the C#'s lock(_lockObj){...} keyword for locking.

Upvotes: 1

Views: 1103

Answers (1)

Craig M
Craig M

Reputation: 81

The runtime guarantees only one copy of a static member field. You can even use it without any instances of the class. It would be safe for use as a lock object.

Upvotes: 2

Related Questions