How to pass a variable from one app domain to another

devoured elysium picture devoured elysium · Aug 9, 2009 · Viewed 13.9k times · Source

I'd like to know, if I have a variable,for example, a string, how to pass its value to my new app domain:

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"
}

Thanks

Answer

Romain Hautefeuille picture Romain Hautefeuille · Sep 25, 2013

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