다음을 통해 공유


AppDomainUnloadedException 클래스

언로드된 응용 프로그램 도메인에 액세스할 때 throw되는 예외입니다.

네임스페이스: System
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class AppDomainUnloadedException
    Inherits SystemException
‘사용 방법
Dim instance As AppDomainUnloadedException
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public class AppDomainUnloadedException : SystemException
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public ref class AppDomainUnloadedException : public SystemException
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public class AppDomainUnloadedException extends SystemException
SerializableAttribute 
ComVisibleAttribute(true) 
public class AppDomainUnloadedException extends SystemException

설명

.NET Framework 버전 2.0에서 사용자 코드에서 처리되지 않는 AppDomainUnloadedException은 다음과 같은 결과를 가져옵니다.

  • 스레드가 관리 코드에서 시작되었으면 종료됩니다. 처리되지 않는 예외는 응용 프로그램을 종료할 수 없습니다.

  • ThreadPool 스레드에서 작업이 실행되고 있으면 이 작업이 종료되고 해당 스레드가 스레드 풀로 반환됩니다. 처리되지 않는 예외는 응용 프로그램을 종료할 수 없습니다.

  • 스레드가 기본 응용 프로그램 스레드와 같은 비관리 코드에서 시작되었으면 종료됩니다. 처리되지 않은 예외는 계속 진행되지 않으며 운영 체제에서 해당 응용 프로그램을 종료합니다.

AppDomainUnloadedException은 0x80131014 값을 가지는 HRESULT COR_E_APPDOMAINUNLOADED를 사용합니다.

AppDomainUnloadedException 인스턴스의 초기 속성 값 목록에 대한 자세한 내용은 AppDomainUnloadedException 생성자를 참조하십시오.

예제

이 단원에는 두 개의 코드 예제가 있습니다. 첫 번째 예제에서는 다양한 스레드에 대한 AppDomainUnloadedException의 결과를 보여 주며 두 번째 예제에서는 기본 응용 프로그램 도메인 언로드를 보여 줍니다.

예제 1

다음 코드 예제에서는 응용 프로그램 도메인 경계를 넘어 마샬링될 수 있는 TestClass 클래스와 static(Visual Basic의 경우 Shared) ThreadProc 메서드가 포함된 Example 클래스를 정의합니다. ThreadProc 메서드는 응용 프로그램 도메인을 만들고, 도메인에 TestClass 개체를 만들고, 실행 도메인을 언로드하는 TestClass의 메서드를 호출하므로 AppDomainUnloadedException이 발생합니다.

TestClass 메서드를 예외 처리 없이 ThreadPool 스레드와 일반 스레드에서 실행하여, 처리되지 않은 예외에 의해 응용 프로그램이 아닌 작업이나 스레드가 종료되는 상황을 보여 줍니다. 그런 다음 예외를 처리하거나 처리하지 않고 이 메서드를 기본 응용 프로그램 스레드에서 실행하여, 예외가 처리되지 않은 경우 응용 프로그램이 종료되는 상황을 보여 줍니다.

Imports System
Imports System.Threading
Imports System.Runtime.InteropServices

Public Class Example
    
    Public Shared Sub Main() 

        ' 1. Queue ThreadProc as a task for a ThreadPool thread.
        ThreadPool.QueueUserWorkItem(AddressOf ThreadProc, _
            " from a ThreadPool thread")
        Thread.Sleep(1000)
        
        ' 2. Execute ThreadProc on an ordinary thread.
        Dim t As New Thread(AddressOf ThreadProc)
        t.Start(" from an ordinary thread")
        t.Join()
        
        ' 3. Execute ThreadProc on the main thread, with 
        '    exception handling.
        Try
            ThreadProc(" from the main application thread (handled)")
        Catch adue As AppDomainUnloadedException
            Console.WriteLine("Main thread caught AppDomainUnloadedException: {0}", _
                adue.Message)
        End Try
        
        ' 4. Execute ThreadProc on the main thread without
        '    exception handling.
        ThreadProc(" from the main application thread (unhandled)")
        
        Console.WriteLine("Main: This message is never displayed.")
    
    End Sub 
    
    Private Shared Sub ThreadProc(ByVal state As Object) 
        ' Create an application domain, and create an instance
        ' of TestClass in the application domain. The first
        ' parameter of CreateInstanceAndUnwrap is the name of
        ' this executable. If you compile the example code using
        ' any name other than "Sample.exe", you must change the
        ' parameter appropriately.
        Dim ad As AppDomain = AppDomain.CreateDomain("TestDomain")
        Dim o As Object = ad.CreateInstanceAndUnwrap("Sample", "TestClass")
        Dim tc As TestClass = CType(o, TestClass)
        
        ' In the new application domain, execute a method that
        ' unloads the AppDomain. The unhandled exception this
        ' causes ends the current thread.
        tc.UnloadCurrentDomain(state)
        
        Console.WriteLine("ThreadProc: This message is never displayed.")
    
    End Sub
End Class 

' TestClass derives from MarshalByRefObject, so it can be marshaled
' across application domain boundaries. 
'
Public Class TestClass
    Inherits MarshalByRefObject
    
    Public Sub UnloadCurrentDomain(ByVal state As Object) 
        Console.WriteLine(vbLf & "Unloading the current AppDomain{0}.", state)
        
        ' Unload the current application domain. This causes
        ' an AppDomainUnloadedException to be thrown.
        '
        AppDomain.Unload(AppDomain.CurrentDomain)
    
    End Sub 
End Class 

' This code example produces output similar to the following:
'
'Unloading the current AppDomain from a ThreadPool thread.
'
'Unloading the current AppDomain from an ordinary thread.
'
'Unloading the current AppDomain from the main application thread (handled).
'Main thread caught AppDomainUnloadedException: The application domain in which the thread was running has been unloaded.
'
'Unloading the current AppDomain from the main application thread (unhandled).
'
'Unhandled Exception: System.AppDomainUnloadedException: The application domain in which the thread was running has been unloaded.
'   at TestClass.UnloadCurrentDomain(Object state)
'   at Example.ThreadProc(Object state)
'   at Example.Main()
' 
using System;
using System.Threading;
using System.Runtime.InteropServices;

public class Example
{
    public static void Main()
    {
        // 1. Queue ThreadProc as a task for a ThreadPool thread.
        ThreadPool.QueueUserWorkItem(ThreadProc, " from a ThreadPool thread");
        Thread.Sleep(1000);

        // 2. Execute ThreadProc on an ordinary thread.
        Thread t = new Thread(ThreadProc);
        t.Start(" from an ordinary thread");
        t.Join();

        // 3. Execute ThreadProc on the main thread, with 
        //    exception handling.
        try
        {
            ThreadProc(" from the main application thread (handled)");
        }
        catch (AppDomainUnloadedException adue)
        {
            Console.WriteLine("Main thread caught AppDomainUnloadedException: {0}", adue.Message);
        }

        // 4. Execute ThreadProc on the main thread without
        //    exception handling.
        ThreadProc(" from the main application thread (unhandled)");

        Console.WriteLine("Main: This message is never displayed.");
    }

    private static void ThreadProc(object state)
    {
        // Create an application domain, and create an instance
        // of TestClass in the application domain. The first
        // parameter of CreateInstanceAndUnwrap is the name of
        // this executable. If you compile the example code using
        // any name other than "Sample.exe", you must change the
        // parameter appropriately.
        AppDomain ad = AppDomain.CreateDomain("TestDomain");
        TestClass tc = (TestClass)ad.CreateInstanceAndUnwrap("Sample", "TestClass");

        // In the new application domain, execute a method that
        // unloads the AppDomain. The unhandled exception this
        // causes ends the current thread.
        tc.UnloadCurrentDomain(state);

        Console.WriteLine("ThreadProc: This message is never displayed.");
    }
}

// TestClass derives from MarshalByRefObject, so it can be marshaled
// across application domain boundaries. 
//
public class TestClass : MarshalByRefObject
{
    public void UnloadCurrentDomain(object state)
    {
        Console.WriteLine("\nUnloading the current AppDomain{0}.", state);
 
        // Unload the current application domain. This causes
        // an AppDomainUnloadedException to be thrown.
        //
        AppDomain.Unload(AppDomain.CurrentDomain);
    }
}

/* This code example produces output similar to the following:
Unloading the current AppDomain from a ThreadPool thread.

Unloading the current AppDomain from an ordinary thread.

Unloading the current AppDomain from the main application thread (handled).
Main thread caught AppDomainUnloadedException: The application domain in which the thread was running has been unloaded.

Unloading the current AppDomain from the main application thread (unhandled).

Unhandled Exception: System.AppDomainUnloadedException: The application domain in which the thread was running has been unloaded.
   at TestClass.UnloadCurrentDomain(Object state)
   at Example.ThreadProc(Object state)
   at Example.Main()
 */

예제 2

다음 코드 예제에서는 응용 프로그램 도메인을 만들어 언로드하고, 언로드한 도메인을 계속 액세스하려고 시도할 때 AppDomainUnloadedException이 throw되는 결과를 보여 줍니다.

Imports System
Imports System.Reflection
Imports System.Security.Policy 'for evidence object

Class ADUnload
   
   Public Shared Sub Main()

      'Create evidence for the new appdomain.
      Dim adevidence As Evidence = AppDomain.CurrentDomain.Evidence

      ' Create the new application domain.
      Dim domain As AppDomain = AppDomain.CreateDomain("MyDomain", adevidence)
      
      Console.WriteLine(("Host domain: " + AppDomain.CurrentDomain.FriendlyName))
      Console.WriteLine(("child domain: " + domain.FriendlyName))
      ' Unload the application domain.
      AppDomain.Unload(domain)
      
      Try
         Console.WriteLine()
         ' Note that the following statement creates an exception because the domain no longer exists.
         Console.WriteLine(("child domain: " + domain.FriendlyName))
      
      Catch e As AppDomainUnloadedException
         Console.WriteLine("The appdomain MyDomain does not exist.")
      End Try
   End Sub 'Main 
End Class 'ADUnload
using System;
using System.Reflection;
using System.Security.Policy;  //for evidence object
class ADUnload
{
    public static void Main()
    {

        //Create evidence for the new appdomain.
        Evidence adevidence = AppDomain.CurrentDomain.Evidence;

        // Create the new application domain.
        AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence);

                Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);
                Console.WriteLine("child domain: " + domain.FriendlyName);
        // Unload the application domain.
        AppDomain.Unload(domain);

        try
        {
        Console.WriteLine();
        // Note that the following statement creates an exception because the domain no longer exists.
                Console.WriteLine("child domain: " + domain.FriendlyName);
        }

        catch (AppDomainUnloadedException e)
        {
        Console.WriteLine("The appdomain MyDomain does not exist.");
        }
        
    }
    
}
using namespace System;
using namespace System::Reflection;
using namespace System::Security::Policy;

//for evidence Object*
int main()
{
   
   //Create evidence for the new appdomain.
   Evidence^ adevidence = AppDomain::CurrentDomain->Evidence;
   
   // Create the new application domain.
   AppDomain^ domain = AppDomain::CreateDomain( "MyDomain", adevidence );
   Console::WriteLine( "Host domain: {0}", AppDomain::CurrentDomain->FriendlyName );
   Console::WriteLine( "child domain: {0}", domain->FriendlyName );
   
   // Unload the application domain.
   AppDomain::Unload( domain );
   try
   {
      Console::WriteLine();
      
      // Note that the following statement creates an exception because the domain no longer exists.
      Console::WriteLine( "child domain: {0}", domain->FriendlyName );
   }
   catch ( AppDomainUnloadedException^ /*e*/ ) 
   {
      Console::WriteLine( "The appdomain MyDomain does not exist." );
   }

}
import System.*;
import System.Reflection.*;
import System.Security.Policy.*; //for evidence object

class ADUnload
{
    public static void main(String[] args)
    {
        // Create evidence for the new appdomain.
        Evidence adEvidence = AppDomain.get_CurrentDomain().get_Evidence();

        // Create the new application domain.
        AppDomain domain = AppDomain.CreateDomain("MyDomain", adEvidence);

        Console.WriteLine("Host domain: " 
            + AppDomain.get_CurrentDomain().get_FriendlyName());
        Console.WriteLine("child domain: " + domain.get_FriendlyName());

        // Unload the application domain.
        AppDomain.Unload(domain);
        try {
            Console.WriteLine();

            // Note that the following statement creates an exception 
            // because the domain no longer exists.
            Console.WriteLine("child domain: " + domain.get_FriendlyName());
        }
        catch (AppDomainUnloadedException e) {
            Console.WriteLine("The appdomain MyDomain does not exist.");
        }
    } //main
} //ADUnload

상속 계층 구조

System.Object
   System.Exception
     System.SystemException
      System.AppDomainUnloadedException

스레드로부터의 안전성

이 형식의 모든 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0에서 지원

참고 항목

참조

AppDomainUnloadedException 멤버
System 네임스페이스
AppDomain 클래스
Exception

기타 리소스

예외 처리 및 Throw