How do I create an application domain and run my application in it?

匆匆过客 提交于 2019-11-27 11:15:13

It should probably be noted that creating AppDomains just to get around something that can be fixed with a constant string is probably the wrong way to do it. If you are trying to do the same thing as the link you noted, you could just do this:

var configFile = Assembly.GetExecutingAssembly().Location + ".config";
if (!File.Exists(configFile))
    throw new Exception("do your worst!");

Recursive Entry Point :o)

static void Main(string[] args)
{
    if (AppDomain.CurrentDomain.IsDefaultAppDomain())
    {
        Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);

        var currentAssembly = Assembly.GetExecutingAssembly();
        var otherDomain = AppDomain.CreateDomain("other domain");
        var ret = otherDomain.ExecuteAssemblyByName(currentAssembly.FullName, args);

        Environment.ExitCode = ret;
        return;
    }

    Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
    Console.WriteLine("Hello");
}

Quick sample using a nonstatic secondary entry point and MarshalByRefObject...

class Program
{
    static AppDomain otherDomain;

    static void Main(string[] args)
    {
        otherDomain = AppDomain.CreateDomain("other domain");

        var otherType = typeof(OtherProgram);
        var obj = otherDomain.CreateInstanceAndUnwrap(
                                 otherType.Assembly.FullName,
                                 otherType.FullName) as OtherProgram;

        args = new[] { "hello", "world" };
        Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
        obj.Main(args);
    }
}

public class OtherProgram : MarshalByRefObject
{
    public void Main(string[] args)
    {
        Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
        foreach (var item in args)
            Console.WriteLine(item);
    }
}

You need to:

1) Create an instance of AppDomainSetup object and populate it with the setup information you want for your domain

2) Create your new domain by using AppDomain.CreateDoman method. The AppDomainSetup instance with configuration parameters is passed to the CreateDomain method.

3) Create an instance of your object in the new domain by using the CreateInstanceAndUnwrap method on the domain object. This method takes typename of the object you want to create and returns a remoting proxy you can use in yuor main domain to communicate with the object created in the new one

Once you are through with these 3 steps you can call methods in the other domain through the proxy. You can also unload the domain after you are done and reload it again.

This topic in MSDN help has pretty detailed example of what you need

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!