BUG: AppDomainUnloaded exception when you use managed extensions for Visual C++ components

Article translations Article translations
Article ID: 309694 - View products that this article applies to.
This article was previously published under Q309694
Expand all | Collapse all

On This Page

SYMPTOMS

This problem occurs when a call is made from unmanaged code to managed code, including direct unmanaged-to-managed calls within a single DLL. For example, the problem may occur when MEC++/IJW is used in ASP.NET applications. In ASP.NET, various events can cause applications to be reloaded into a new AppDomain. If you are using MEC++ components and IJW in this application, you may receive an AppDomainUnloadException error message.

CAUSE

As part of the implementation of IJW, when a managed DLL that you created by using the C++ compiler loads, the runtime creates thunks for transitions from unmanaged code to managed code. These thunks contain a reference to the AppDomain in which the DLL loads. The runtime does not re-create these thunks if the DLL loads again; also, the runtime does not update the reference when the original AppDomain unloads and the DLL loads in another AppDomain.

When the program performs a transition from unmanaged code to managed code, the program uses the outdated AppDomain reference to run the managed code. Even if the original AppDomain is still loaded, the code cannot access static fields because the fields are specific to the AppDomain.

WORKAROUND

The following workarounds are grouped according to two scenarios:
  • A transition from unmanaged code to managed code across two DLLs
  • A transition from unmanaged code to managed code in the same DLL

Unmanaged Code to Managed Code Transition Across Two DLLs

Use either of the following methods to resolve this specific problem.

Workaround 1

For ASP.NET clients, allow the ASP.NET host process to shut down by trapping the DomainUnload event. However, you must first register a delegate for the DomainUnload event. To do this, follow these steps:
  1. In the Application_Start method of the ASP.NET Application class, register a delegate to be called when the AppDomain unloads.
  2. In the registered delegate, shut down the Aspnet_wp.exe process.
Note This workaround causes all of the ASP.NET applications on the computer to restart; the in-process session state data for all of these applications is lost. In Internet Information Service (IIS) 6.0 on a computer that is running Windows 2003 Server, you can configure the program for one application per process mode. For more information about configuing application pools, visit the following Microsoft Web site:
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/2a231dcb-d786-4b6d-b3ba-bda04061a5e7.mspx?mfr=true
//Register a delegate to be called when the DomainUnload event fires.
protected void Application_Start(Object sender, EventArgs e)
{
     AppDomain.CurrentDomain.DomainUnload+= new EventHandler(ADUnloading);
}

//This method is called when the AppDomain is about to unload.
public void ADUnloading(object s, EventArgs e)
{
     System.Environment.Exit(0);
}
				

Workaround 2

Replace all transitions from unmanaged code to managed code with calls through an unmanaged function pointer that you create by using a delegate (which is AppDomain specific). The delegate is marshaled to the unmanaged code by using Platform Invocation Services (P/Invoke) instead of IJW.

For the unmanaged DLL described in the "More Information" section of this article, the following sample code demonstrates how to use P/Invoke to use the callback method:
using namespace System::Runtime::InteropServices; // For DllImportAttribute.

namespace ManagedLib
{
        //Managed delegate declaration.
	public __delegate int ManagedFuncDelg();
	public __gc class Class1
	{
		
	public:
		[DllImport("Win32.dll", EntryPoint="callback")]//Assumes that you have a DEF file for the exports.
		static int Mgdcallback(ManagedFuncDelg*);
                //This method is called from the unmanaged DLL.
		static int InternalMethod()
		{
			return 123;
		}

		static ManagedFuncDelg* pd = new ManagedFuncDelg(0, &ManagedLib::Class1::InternalMethod);

                //This method is called by the client application.
		int Func()
		{
			int ret = ManagedLib::Class1::Mgdcallback(ManagedLib::Class1::pd);
			return ret;
		}
	};
}
				

Unmanaged Code to Managed Code Transition in the Same DLL

In this scenario, you can have unmanaged methods (marked with #pragma unmanaged) calling methods on a managed component in the same DLL, as shown in the "More Information" section of this article. Use either of the following methods to resolve this specific issue:

Workaround 1

Marshal your function pointer as a delegate and use that delegate. Because you cannot use P/Invoke on the same DLL, create a wrapper DLL that helps you to marshal a delegate to a function pointer. This exported function returns the address of the delegate that is passed to it. The following sample code is an example of this workaround:
//This is the helper DLL that enables you to marshal the delegate.
//Helper.cpp.
//Helper DLL code.
extern "C" __declspec(dllexport) void* __stdcall FuncInUmDll(void* pv)
{
	return pv;
}
				
The following sample code is for the Managed Extensions for C++ assembly that uses the previous Helper.dll:
#using <mscorlib.dll>
using namespace System;
using namespace System::Runtime::InteropServices; // for DllImportAttribute

namespace ManagedLib
{
      //Forward declaration.
      __delegate int delg();
      int nativefunc(int(__stdcall*)());
      [System::Runtime::InteropServices::DllImport("helper.dll", EntryPoint="FuncInUmDll")] int FuncInUmDll(delg*);
      //Managed component.
      public __gc class Class1{
	public:
            static int InternalMethod()
            {
                 return 123;
            }

            //This method is called by the client application.
            int Func()
            {
                 delg* d= new delg(0, &Class1::InternalMethod);
                 int ret = nativefunc((int(__stdcall*)())FuncInUmDll(d));
                 return ret;
            }
      };


      #pragma unmanaged
     //Unmanaged function calling the managed delegate.
     int nativefunc(int(__stdcall*pf)())
     {
            return pf();
     }
}
				

Workaround 2

Split your MEC++ assembly into two DLLs, one that contains only managed components and other that contains only unmanaged components, and then use P/Invoke as described in workaround 2 of scenario 1.

STATUS

Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.

MORE INFORMATION

The problem is more prevalent if the host or client application must unload and reload AppDomains and the application contains transitions from unmanaged code to managed code that use MEC++ and IJW components. ASP.NET is one good example of such a host. In ASP.NET, the events that can trigger an AppDomain unload event can be anything from crossing a memory usage threshold to touching certain files (for example, Machine.config).

Steps to Reproduce Behavior

In this example, you have an ASP.NET application that calls a MEC++ component, and this component has a function pointer that points to one of the methods in the MEC++ component. The component passes the function pointer to one of the following:
  • a function that was exported by an unmanaged DLL
  • an unmanaged method in the same DLL
The unmanaged code then makes a callback by using the function pointer that was received from the MEC++ component.

In the following scenarios, it is possible that, before the unmanaged function invokes the function pointer, the original AppDomain in which the DLL was loaded is unloaded. Under such conditions, the unmanaged code still references the original AppDomain and tries to call to managed code in that context.
  • Unmanaged Code to Managed Code Transition Across Two DLLs

    Call an exported unmanaged DLL function from a MEC++ assembly in one of the following ways:
    • by using IJW
    • by using P/Invoke
    The following sample code uses an unmanaged DLL (Win32.dll) that exports a method.
    //Win32.h.
    #ifdef WIN32_EXPORTS
    #define WIN32_API __declspec(dllexport)
    #else
    #define WIN32_API __declspec(dllimport)
    #endif
    
    //Declaration.
    typedef int (__stdcall *funcptr)(void);
    WIN32_API int __stdcall  callback(funcptr ptr);
    
    //Win32.cpp Implementation.
    //This method is called by the Managed C++ component either by using P/Invoke
    //or by using IJW.
    WIN32_API int __stdcall callback(funcptr ptr)
    {
    	int rtn= ptr();
    	return rtn;
    }
    					
    A managed C++ assembly can call this method through IJW by linking to the Win32.lib and by including the appropriate header file. The following sample code shows how to use the exported method.
    #pragma once
    #include "win32.h"
    #using <mscorlib.dll>
    using namespace System;
    
    namespace ManagedLib
    {
    
    	public __gc class Class1
    	{
    		
    	public:
    		static int InternalMethod()
    		{
    			return 123;
    		}
    
                    //This method is called by the client application.
    		int Func()
    		{
    			int ret = callback((funcptr)Class1::InternalMethod);
    			return ret;
    		}
    	};
    }
    					
  • Unmanaged Code to Managed Code Transition in the Same DLL

    In this scenario, the MEC++ assembly contains unmanaged methods (marked with #pragma unmanaged) that call methods on a MEC++ component in the same DLL, as shown in the following sample code.
    #using <mscorlib.dll>
    using namespace System;
    namespace ManagedLib
    {
          //Forward declararion
          int nativefunc(int(__stdcall*)());
          //Managed component
          public __gc class Class1{
    
    	public:
    
                static int InternalMethod()
                {
                     return 123;
                }
                //This method is called by the client application.
                int Func()
                {
                     int ret = nativefunc((int(__stdcall*)())Class1::InternalMethod);
                     return ret;
                }
          };
    
          #pragma unmanaged
         //Unmanaged function calling the managed delegate.
         int nativefunc(int(__stdcall*pf)())
         {
                return pf();
         }
    }
    					

REFERENCES

For more information, visit the following Microsoft Developer Network (MSDN) Web sites:
Application Domains
http://msdn2.microsoft.com/en-us/library/cxk374d9(vs.71).aspx?frame=true

AppDomain Class
http://msdn2.microsoft.com/en-us/library/system.appdomain(vs.71).aspx

AppDomainUnloadedException Class
http://msdn.microsoft.com/en-us/library/system.appdomainunloadedexception(VS.71).aspx

Managed Extensions for C++ Programming
http://msdn2.microsoft.com/en-us/library/aa712574(vs.71).aspx

Creating ASP.NET Web Applications
http://msdn.microsoft.com/en-us/library/aa719794.aspx

Worker Process Isolation Mode
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/34604f82-9175-4d48-b5ea-1e11f19db5f3.mspx?mfr=true

Properties

Article ID: 309694 - Last Review: May 17, 2007 - Revision: 4.7
APPLIES TO
  • Microsoft Visual C++ .NET 2002 Standard Edition
  • Microsoft .NET Framework 1.0
Keywords: 
kbbug kbijw kbmanaged kbpending KB309694

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com