Why does Unity create A first chance exception of type 'System.Threading.SynchronizationLockException' during startup

Jun 29, 2009 at 2:02 PM

Unity appears to use exceptions as flowcontrol during startup.  This makes debugging VERY hard when break on exception is turned on.  The specific error message is

A first chance exception of type 'System.Threading.SynchronizationLockException' occurred in Microsoft.Practices.Unity.dll

 

Jun 30, 2009 at 4:43 AM

See here: http://www.tavaresstudios.com/Blog/post/Writing-Custom-Lifetime-Managers.aspx

Jul 25, 2009 at 12:52 AM

It's clear why it happens, but not clear why not to change the way SynchronizedLifetimeManager works.

The problem is here:

private void TryExit()
        {
            try
            {
                Monitor.Exit(lockObj);
            }
            catch (SynchronizationLockException)
            {
                // Noop here - we don't hold the lock and that's ok.
            }
        }

If we are debudding with the option "break at throw" turned on then we break at EVERY type registration . It's pain.

Why not do something like this:

[ThreadStatic]
private bool is_locked;

public override object GetValue()
{
    Monitor.Enter(lockObject);
    if(value != null)
        Monitor.Exit(lockObject);
    else
        is_locked = true;
    return value;
}

private void TryExit(object lockObj)
{
    if(!is_locked) return;
    Monitor.Exit(lockObj);
    is_locked = false;
}

There's no exceptions now.