How to pass a variable from one app domain to another

痞子三分冷 提交于 2019-12-04 23:10:01
Oren Trutner

Use one of the variations of AppDomain.CreateDomain that takes an AppDomainSetup argument. In the AppDomainSetup object, set the AppDomainInitializerArguments member to the string array you want passed to the new app domain.

See sample code at http://msdn.microsoft.com/en-us/library/system.appdomainsetup.appdomaininitializerarguments.aspx.

With the code in the question, the change might look like (not tested):

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) {
    ...
}

Addressing both your first and second requirements (passing through a value and retrieving another value back), here is a quite simple solution:

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");
}
Leo

I know that this is an old thread but perhaps this will help other people who are researching the subject.

In this article, the writer suggests using application domain SetData and GetData methods for basic exchange of data objects that support marshal-by-value or marshal-by-reference object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!