application domains and threads

流过昼夜 提交于 2019-12-10 23:38:43

问题


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?


回答1:


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



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/675089/application-domains-and-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!