Subscribe

RSS Feed (xml)

Execute an Assembly in a Different Application Domain

If you have an executable assembly that you want to load and run in an application domain, the ExecuteAssembly method provides the easiest solution. The ExecuteAssembly method provides four overloads. The simplest overload takes only a string containing the name of the executable assembly to run; you can specify a local file or a URL. Other ExecuteAssembly overloads allow you to specify evidence for the assembly and arguments to pass to the assembly's entry point (equivalent to command-line arguments).
The ExecuteAssembly method loads the specified assembly and executes the method defined in metadata as the assembly's entry point (usually the Main method). If the specified assembly isn't executable, 
ExecuteAssembly throws a System.Runtime.InteropServices.COMException. The CLR doesn't start execution of the assembly in a new thread, so control won't return from the ExecuteAssembly method until the newly executed assembly exits. Because the ExecuteAssembly method loads an assembly using partial information (only the filename), the CLR won't use the GAC or probing to resolve the assembly.
The following example demonstrates the use of the ExecuteAssembly method to load and run an assembly. The ExecuteAssemblyExample class creates an AppDomain and executes itself in that AppDomain using the ExecuteAssembly method. This results in two copies of the ExecuteAssemblyExample assembly loaded into two different application domains.
 
using System;

public class ExecuteAssemblyExample {

public static void Main(string[] args) {

        // For the purpose of this example, if this assembly is executing
        // in an AppDomain with the friendly name "NewAppDomain", do not 
        // create a new AppDomain. This avoids an infinite loop of 
        // AppDomain creation.
        if (AppDomain.CurrentDomain.FriendlyName != "NewAppDomain") {

            // Create a new application domain
            AppDomain domain = AppDomain.CreateDomain("NewAppDomain");

            // Execute this assembly in the new application domain and
            // pass the array of command-line arguments.
            domain.ExecuteAssembly("ExecuteAssemblyExample.exe", 
                null, args);
        }

        // Display the command-line arguments to the screen prefixed with
        // the friendly name of the AppDomain.
        foreach (string s in args) {

            Console.WriteLine(AppDomain.CurrentDomain.FriendlyName + 
                " : " + s);
        }
    }
}

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail