Search code examples
c#lockingparallel-processinggarbage

Does lock allocate


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)

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?