views:

238

answers:

3

A quote from MSDN: http://msdn.microsoft.com/en-us/library/6kac2kdh.aspx

One or more managed threads (represented by System.Threading.Thread) can run in one or any number of application domains within the same managed process. Although each application domain is started with a single thread, code in that application domain can create additional application domains and additional threads. The result is that a managed thread can move freely between application domains inside the same managed process; you might have only one thread moving among several application domains.

I tried to write code with 2 application domains that share one thread. But i gave up. I have really no idea how this is possible. Could you give me a code sample for this?

+4  A: 

This can be done by simply creating an object which is MarshalByRef in a separate AppDomain and then calling a method on that object.

Take for example the following class definition.

public interface IFoo
{
    void SomeMethod();
}

public class Foo : MarshalByRefObject, IFoo
{
    public Foo()
    {
    }

    public void SomeMethod()
    {
        Console.WriteLine("In Other AppDomain");
    }
}

You can then use this definition to call into a separate AppDomain from the current one. At the point the call writes to the Console you will have 1 thread in 2 AppDomains (at 2 different points in the call stack). Here is the sample code for that.

public static void CallIntoOtherAppDomain()
{
    var domain = AppDomain.CreateDomain("Other Domain");
    var obj = domain.CreateInstanceAndUnwrap(typeof(Foo).Assembly.FullName, typeof(Foo).FullName);
    var foo = (IFoo)obj;
    foo.SomeMethod();
}
JaredPar
so Thread.GetDomain() is not fixed to the appdomain who created the thread. it is dynamic based on the current callstack... no i understand! thanks a lot!
michl86
A: 

Call a method on an object of the other app domain.

Lars Truijens
A: 

This may be because English is not my first language, but the documentation is a little confusing to me.

Just to clarify when you create new AppDomains, you do not get additional threads. If you call methods via the MarshalByRef proxy this is done via the main thread unless you create additional threads yourself.

I.e. the default behavior when creating additional AppDomains is that one thread will be shared between the different AppDomains.

Brian Rasmussen
i'm not sure why this is so, but it looks so...
michl86