gpt4 book ai didi

.NET AppDomain 混淆

转载 作者:行者123 更新时间:2023-12-04 06:41:11 26 4
gpt4 key购买 nike

我一直无法找到关于使用 AppDomains 时发生的事情的非常清楚的描述,所以希望有人能够启发我。我有一个简单的测试程序(基本上是扯掉了 MSDN example ):

using System;
using System.Reflection;

class Program
{
public static void Main(string[] args)
{
A localA = new A() { Name = "local" };
localA.PrintAppDomain();

AppDomain domain = AppDomain.CreateDomain("NewDomain");
A remoteA = (A)domain.CreateInstanceAndUnwrap(
Assembly.GetExecutingAssembly().FullName, "A");
remoteA.Name = "remote";
remoteA.PrintAppDomain();

remoteA.PrintA(localA);
remoteA.PrintAppDomain();
}
}

[Serializable]
public class A : MarshalByRefObject
{
public string Name { get; set; }

public void PrintAppDomain()
{
Console.WriteLine("In AppDomain {1}",
this.Name, AppDomain.CurrentDomain.FriendlyName);
}

public void PrintA(A a)
{
Console.WriteLine(a.ToString());
}

public override string ToString()
{
return String.Format("A : {0}", this.Name);
}
}

运行时,这会打印出来

In AppDomain test.exe
In AppDomain NewDomain
A : local
In AppDomain NewDomain



所以...当我这样做时 remote.PrintA(localA) ,这是否涉及编码?查看 Reflector 中的 IL 表明不会,但我认为一个 AppDomain 中的数据无法访问来自另一个 AppDomain 的数据。

如果我删除 : MarshalByRefObject来自 A 的声明,程序打印

In AppDomain test.exe
In AppDomain test.exe
A : local
In AppDomain test.exe



在这种情况下发生了什么?是否正在创建新的 AppDomain?

最佳答案

你看到的行为很正常。

如果删除 MarshalByRefObject , 因为你有 Serializable属性,远程处理将为您序列化该类并编码 状态到主 AppDomain。因此,当该方法运行时,in 会在当前 AppDomain 中运行,因为它位于主 AppDOmain(已序列化并编码到当前 AppDomain)中。

如果您保留 MarshalByRefObject , 远程处理将对远程对象进行调用。

如果您同时删除两者,则会引发异常,因为远程处理对象需要有一个。

关于.NET AppDomain 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4213510/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com