Darren
Darren

Reputation: 4488

"LoaderLock was detected" with Visual Studio 2012

I have a couple of MVC projects which use SQL CE 4.0 and Entity Framework. Since moving to Visual Studio 2012 I keep getting the following error (not every time, but frequently)

LoaderLock was detected

Attempting managed execution inside OS Loader lock. Do not attempt to run managed code inside a DllMain or image initialization function since doing so can cause the application to hang.

The error does not occur if I go back to using VS 2010, which makes me fairly certain it is an issue with Visual Studio rather than my code, but I would like someone to confirm that for me!

Edit

The problem always seems to occur when the Dispose() method of the dbcontext is called. Here is a screenshot of the Exception Assistant:

Exception Assistant

Upvotes: 25

Views: 17662

Answers (3)

William Shen
William Shen

Reputation: 9

It may happen with compiler warning C4747.

To avoid this, make DllMain unmanaged.

For example:

#include "pch.h"
#pragma unmanaged // <- add this line just after include to make code after this be unmanaged.
BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

or

#include "pch.h"
#pragma managed(push, off) // <- add this line before function DllMain
BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}
#pragma managed(pop) // <- add this line after function DllMain to make code below managed.

Upvotes: 0

harriyott
harriyott

Reputation: 10645

I switch this off. As it is warning that the application could hang, if your program doesn't hang, then you're probably fine.

The problem can be solved in the same way though, by switching off the MDA:

Debug -> Exceptions -> Managed Debug Assistants

and unchecking the LoaderLock item.

Upvotes: 14

rebeliagamer
rebeliagamer

Reputation: 1278

I also had a problem with LoaderLock when I was working with some external dll in my C# application.

  • for the .NET 3.5 I just uncheck Thrown option in Exceptions menu (Loader lock error)
  • for the .NET 4.0 I added <startup useLegacyV2RuntimeActivationPolicy="true"> in app.config

Upvotes: 5

Related Questions