如何创建应用程序域并在其中运行我的应用程序? [英] How do I create an application domain and run my application in it?

查看:25
本文介绍了如何创建应用程序域并在其中运行我的应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to create a custom application domain to work around a bug in the .NET runtime's default behavior. None of the sample code I've seen online is helpful since I don't know where to place it, or what it needs to replace within my Main() method.

推荐答案

可能应该注意的是,创建 AppDomains 只是为了解决可以用常量字符串修复的问题可能是错误的方法.如果您试图做与您注意到的链接相同的事情,您可以这样做:

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!");

递归入口点 :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");
}

使用非静态辅助入口点和 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);
    }
}

这篇关于如何创建应用程序域并在其中运行我的应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆