Question

I read somewhere, although I can't remember where, that using the lock keyword in C# can allocate.

I know that trying to lock a ValueType will box the valuetype, but are there any other situations?

EDIT::

  1. Everyone seems to be answer the valuetype case, I already know this!
  2. I also know what locks are and how to use them in great depth, general advice on best practice is nice - but useless ;)
  3. I need to know because I'm building an XNA app for deployment on the xbox. The xbox garbage collector is really slow - this means I need to keep allocations to a minimum, preferably non-existent (which prevents the collector from ever running)
Was it helpful?

Solution

While the allocation of see sync block internally is lazy (but that's an implementation detail which IIRC I know from Essential.NET 'volume 1', or is it CLR via C# - and should be treated as just that), the simple case of the item needing to be boxed like you're suggesting doesn't arise - see Why lock(<integer var>) is not allowed, but Monitor.Enter(<integer var>) allowed?

OTHER TIPS

If you were thinking of using:

lock(this)

You should know that because you're looking on your instance, users of your class could also lock on it and screw you up. Whether or not that is an issue depends on what you think your users might do. The same situation exists if you're doing:

lock(typeof(MyClass))

If you don't want to do this, you can easily allocate a static or instance object (ie object myLock = new object()), and then lock on that.

Source

As far as locking on a reference type vs value type, this SO question on Locking a resource when obtained... has the answer:

It depends on the type - if a reference type then yes, if a value type no. This is also why you should never, ever lock on a value type since the value type will be boxed and any subsequent attempts to lock on that value will actually acquire a lock on a different object.

Definition of lock statement:

lock Statement (C# Reference)

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock.

This SO question on lock keyword in C# may be able to help. You can also look at Why lock() is not allowed, but Monitor.Enter() allowed?

The specification for the compiler defines the behavior of lock like so:

The compile time type of the expression of a lock statement shall be a reference-type or a > type parameter (§25.1.1) known to be a reference type. It is a compile-time error for the compile time type of the expression to denote a value-type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top