【问题标题】:How to pass a variable from one app domain to another如何将变量从一个应用程序域传递到另一个应用程序域
【发布时间】:2010-11-18 01:14:15
【问题描述】:

我想知道,如果我有一个变量,例如一个字符串,如何将它的值传递给我的新应用程序域:

static string _str;

static void Main(string[] args) {
    _str = "abc";
    AppDomain domain = AppDomain.CreateDomain("Domain666");
    domain.DoCallBack(MyNewAppDomainMethod);
    AppDomain.Unload(domain);
    Console.WriteLine("Finished");
    Console.ReadKey();
}

static void MyNewAppDomainMethod() {
    Console.WriteLine(_str); //want this to print "abc"
}

谢谢

【问题讨论】:

    标签: c# .net vb.net cross-domain appdomain


    【解决方案1】:

    使用采用 AppDomainSetup 参数的 AppDomain.CreateDomain 变体之一。在 AppDomainSetup 对象中,将 AppDomainInitializerArguments 成员设置为要传递给新应用域的字符串数组。

    http://msdn.microsoft.com/en-us/library/system.appdomainsetup.appdomaininitializerarguments.aspx查看示例代码。

    使用问题中的代码,更改可能看起来像(未测试):

    static voide Main(string[] args) {
        _str = "abc";
    
        AppDomainSetup setup = new AppDomainSetup();
        setup.AppDomainInitializer = new AppDomainInitializer(MyNewAppDomainMethod);
        setup.AppDomainInitializerArguments = new string[] { _str };
    
        AppDomain domain = AppDomain.CreateDomain(
            "Domain666",
            new Evidence(AppDomain.CurrentDomain.Evidence),
            setup);
    
        Console.WriteLine("Finished");
        Console.ReadKey();
    }
    
    static void MyNewAppDomainMethod(string[] args) {
        ...
    }
    

    【讨论】:

    • 谢谢。现在我想知道如何将信息返回到我的主 appdomain。也就是说,返回一个对象。谢谢!
    • 还有一个问题。我看到 AppDomainInitializerArguments 只接受一个字符串数组。在这种情况下我真的只想要字符串,所以没有问题,但是如果我想要其他类型的数据呢?无事可做?
    • 应用程序域不共享对象内存空间,因此传递对象需要某种序列化。要返回一个对象,你可以在原始的 appdomain 上 DoCallBack,如果你能得到它(虽然我没有看到一个简单的方法)。或者,您可以在应用程序域之间建立某种其他形式的进程间通道,例如命名管道。
    【解决方案2】:

    我知道这是一个旧线程,但也许这会对正在研究该主题的其他人有所帮助。

    this article 中,作者建议使用应用程序域SetDataGetData 方法进行支持按值封送或按引用封送对象的数据对象的基本交换。

    【讨论】:

      【解决方案3】:

      满足您的第一个和第二个要求(传递一个值并检索另一个值),这是一个非常简单的解决方案:

      static void Main(string[] args)
      {
          AppDomain domain = AppDomain.CreateDomain("Domain666");
          domain.SetData("str", "abc");
          domain.DoCallBack(MyNewAppDomainMethod);
          string str = domain.GetData("str") as string;
          Debug.Assert(str == "def");
      }
      
      static void MyNewAppDomainMethod()
      {
          string str = AppDomain.CurrentDomain.GetData("str") as string;
          Debug.Assert(str == "abc");
          AppDomain.CurrentDomain.SetData("str", "def");
      }
      

      【讨论】:

      • 很好的简单解决方案。谢谢。我想强调的是回调函数必须声明为静态的,否则你不能在新的 AppDomain 中工作。 X
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多