如何跨 AppDomains 将引用作为方法参数传递? [英] How do I pass references as method parameters across AppDomains?

查看:27
本文介绍了如何跨 AppDomains 将引用作为方法参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使以下代码工作(所有内容都在同一个程序集中定义):

I have been trying to get the following code to work(everything is defined in the same assembly) :

namespace SomeApp{

public class A : MarshalByRefObject
{
   public byte[] GetSomeData() { // }
}

public class B : MarshalByRefObject
{
   private A remoteObj;

   public void SetA(A remoteObj)
   {
      this.remoteObj = remoteObj;
   }
}

public class C
{
   A someA = new A();
   public void Init()
   {
       AppDomain domain = AppDomain.CreateDomain("ChildDomain");
       string currentAssemblyPath = Assembly.GetExecutingAssembly().Location;
       B remoteB = domain.domain.CreateInstanceFromAndUnwrap(currentAssemblyPath,"SomeApp.B") as B;
       remoteB.SetA(someA); // this throws an ArgumentException "Object type cannot be converted to target type."
   }
}

}

我想要做的是将在第一个 AppDomain 中创建的A"实例的引用传递给子域,并让子域在第一个域上执行一个方法.在'B' 代码的某个时刻,我将调用'remoteObj.GetSomeData()'.必须这样做,因为必须在第一个应用程序域上计算"来自GetSomeData"方法的byte[]".我应该怎么做才能避免异常,或者我该怎么做才能达到相同的结果?

What I'm trying to do is pass a reference of an 'A' instance created in the first AppDomain to the child domain and have the child domain execute a method on the first domain. In some point on 'B' code I'm going to call 'remoteObj.GetSomeData()'. This has to be done because the 'byte[]' from 'GetSomeData' method must be 'calculated' on the first appdomain. What should I do to avoid the exception, or what can I do to achieve the same result?

推荐答案

我可以重复这个问题,它似乎与 TestDriven.net 和/或 xUnit.net 有关.如果我将 C.Init() 作为测试方法运行,我会收到相同的错误消息.但是,如果我从控制台应用程序运行 C.Init(),则不会出现异常.

I can duplicate the issue, and it seems to be related to TestDriven.net and/or xUnit.net. If I run C.Init() as a test method, I get the same error message. However, if I run C.Init() from a console application, I do not get the exception.

从单元测试中运行 C.Init() 是否看到同样的事情?

Are you seeing the same thing, running C.Init() from a unit test?

我还可以使用 NUnit 和 TestDriven.net 复制该问题.我还可以使用 NUnit runner 而不是 TestDriven.net 来复制错误.所以问题似乎与通过测试框架运行此代码有关,但我不确定为什么.

I'm also able to duplicate the issue using NUnit and TestDriven.net. I'm also able to duplicate the error using the NUnit runner instead of TestDriven.net. So the problem seems to be related to running this code through a testing framework, though I'm not sure why.

这篇关于如何跨 AppDomains 将引用作为方法参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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