如何创建应用程序域并在其中运行我的应用程序?

Dan*_*ely 23 c# appdomain

我需要创建一个自定义应用程序域来解决.NET运行时默认行为中的错误.我在网上看到的示例代码都没有用,因为我不知道在哪里放置它,或者在我的Main()方法中需要替换它.

Mat*_*ted 40

应该注意的是,创建AppDomain只是为了解决可以用常量字符串修复的东西可能是错误的方法.如果您尝试执行与您提到的链接相同的操作,则可以执行以下操作:

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

递归入口点: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");
}
Run Code Online (Sandbox Code Playgroud)

使用非静态辅助入口点和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);
    }
}
Run Code Online (Sandbox Code Playgroud)


mfe*_*old 6

你需要:

1)创建AppDomainSetup对象的实例,并使用您想要的域设置信息填充它

2)使用AppDomain.CreateDoman方法创建新域.具有配置参数的AppDomainSetup实例将传递给CreateDomain方法.

3)使用域对象上的CreateInstanceAndUnwrap方法在新域中创建对象的实例.此方法获取您要创建的对象的typename,并返回一个远程代理,您可以在yuor主域中使用该远程代理与在新域中创建的对象进行通信

完成这3个步骤后,您可以通过代理调用其他域中的方法.您也可以在完成后卸载域并重新加载.

MSDN帮助中的这个主题提供了您需要的非常详细的示例

  • 这或多或少是我在其他地方看到的例子中看到的,但没有提供我仍然缺乏的任何信息.我只是调用Application.Run(new MyForm)吗?我是否从我的Main方法中删除所有现有的启动代码,用新方法填充它,并调用它来启动我的应用程序?以上都不是因为我比我想的更困惑? (2认同)