application domains and threads

2019-07-08 16:47发布

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?

3条回答
男人必须洒脱
2楼-- · 2019-07-08 17:27

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

查看更多
【Aperson】
3楼-- · 2019-07-08 17:31

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();
}
查看更多
我命由我不由天
4楼-- · 2019-07-08 17:39

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.

查看更多
登录 后发表回答