代码改变世界

应用程序域的使用 AppDomain

2013-01-08 12:53  panmin  阅读(302)  评论(0)    收藏  举报

1、加载和卸载域

static void Main()
{
    // Create an Application Domain:
    System.AppDomain newDomain = System.AppDomain.CreateDomain("NewApplicationDomain");

// Load and execute an assembly:
    newDomain.ExecuteAssembly(@"c:\HelloWorld.exe");

// Unload the application domain:
    System.AppDomain.Unload(newDomain);
}

 

 

2、在另一个应用程序域中执行代码

// This namespace contains code to be called.
namespace HelloWorldRemote
{
    public class RemoteObject : System.MarshalByRefObject//必须是继承这个类
    {
        public RemoteObject()
        {
            System.Console.WriteLine("Hello, World! (RemoteObject Constructor)");
        }
    }
    class Program
    {
        static void Main()
        {
 

System.AppDomain NewAppDomain = System.AppDomain.CreateDomain("NewApplicationDomain");

// Load the assembly and call the default entry point:
    NewAppDomain.ExecuteAssembly(@"c:\HelloWorldRemote.exe");

// Create an instance of RemoteObject:
    NewAppDomain.CreateInstanceFrom(@"c:\HelloWorldRemote.exe", "HelloWorldRemote.RemoteObject");

            // This code creates an instance of RemoteObject, assuming HelloWorldRemote has been added as a reference:
            HelloWorldRemote.RemoteObject o = new HelloWorldRemote.RemoteObject();

        }
    }
}

源文档http://msdn.microsoft.com/zh-cn/library/ms173140(v=vs.80).aspx