Matthew Scharley
Matthew Scharley

Reputation: 132274

AppDomain and threading

Basically, from what I've understood of the little I've managed to search up on the internet, threads can pass between AppDomains. Now, I've written the following code:

    const string ChildAppDomain = "BlahBlah";
    static void Main()
    {
        if (AppDomain.CurrentDomain.FriendlyName != ChildAppDomain)
        {
            bool done = false;
            while (!done)
            {
                AppDomain mainApp = AppDomain.CreateDomain(ChildAppDomain, null, AppDomain.CurrentDomain.SetupInformation);
                try
                {
                    mainApp.ExecuteAssembly(Path.GetFileName(Application.ExecutablePath));
                }
                catch (Exception ex)
                {
                    // [snip]
                }
                AppDomain.Unload(mainApp);
            }
        }
        else
        {
            // [snip] Rest of the program goes here
        }
    }

This works fine and everything is clicking into place... The main thread passes through into the new version of my program and starts running through the main application body. My question is, how would I go about getting it to go back out to the parent AppDomain? Is this possible? What I'm trying to achieve is sharing an instance of a class between the two domains.

Upvotes: 4

Views: 2733

Answers (2)

JaredPar
JaredPar

Reputation: 754763

An object in .Net can only exist in one AppDomain. It is not possible for it to exist in 2 AppDomains at the same time.

However you can use .Net Remoting to push a proxy of a .Net object into several AppDomains at once time. This will give your object the appearance of being in multiple domains. I believe this is what you are looking for.

There are many tutorials available online. Google for ".Net Remoting Tutorial" and that will put you on teh right track.

Upvotes: 1

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421998

You cannot share instances of classes directly between AppDomains. To do so, you should derive the class from MarshalByRefObject and use remoting to access the instance from the other AppDomain.

Upvotes: 7

Related Questions