2

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?

Michael Piendl
  • 2,864
  • 1
  • 27
  • 21

2 Answers2

8

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();
}
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 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! – Michael Piendl Mar 23 '09 at 20:44
0

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

Lars Truijens
  • 42,837
  • 6
  • 126
  • 143