线程跨应用程序域的简单示例?
我已经阅读了一些有关应用程序域和线程的内容,并且遇到了这样的说法:
“特定线程并不局限于单个应用程序域。也就是说,线程可以自由地跨越应用程序域边界;不会为每个应用程序域创建新线程。”
现在一切都很好,但我心想 - 线程的域交叉到底什么时候会发生?
我见过人们创建应用程序域并使用 CreateInstanceAndUnwrap 和 MarshalByRefObject 的示例。但是 - 在完全独立的进程之间可以进行编组!所以嗯——这不是我所说的“自由穿越”。
任何人都可以提供跨应用程序域的线程的示例(C#)代码而不进行编组,因为我不认为这是“免费的”? (或者我只是像往常一样完全混乱)。
I've been reading up a bit on Application Domains and Threading, and I came across this statement:
"A particular thread is not confined to a single application domain. That is, threads are free to cross application domain boundaries; a new thread is not created for each application domain."
Now that's all well and good, but I thought to myself - when exactly is that crossing of domains by the thread going to happen?
I have seen examples of people creating Application Domains and using CreateInstanceAndUnwrap and MarshalByRefObject. But - marshalling is available between completely seperate processes! So meh - that's not what I call "free to cross".
Can anyone provide example (C#) code of a thread crossing application domains without marshalling, as I do not consider this "free"? (or am I just totally muddled up as usual).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
嗯,很简单,CreateInstanceAndUnwrap() 使线程跨越 AppDomain 屏障。毕竟,创建的对象存在于AD中,线程必须进行转换才能调用构造函数。当您随后通过代理进行调用以调用类方法时,会发生额外的交叉。
AppDomain 并不是代码的屏障,它隔离了数据。每个AD都有自己的GC和加载器堆。需要序列化来跨越该数据障碍。但再次反序列化并继续执行的是完全相同的线程。这与进程之间的编组完全不同,后者必须发生在两个不同的线程之间。在不同的虚拟内存视图和所需的线程上下文切换之间进行封送会产生相当大的开销。 AD 是流程的一个更便宜版本。
Well, simple, CreateInstanceAndUnwrap() makes the thread cross the AppDomain barrier. After all, the created object exists in the AD, the thread must make the transition in order to call the constructor. Additional crossing happen when you then make calls through the proxy to call the class methods.
And AppDomain is not a barrier for code, it isolates data. Each AD has its own GC and loader heap. Serialization is required to cross that data barrier. But it is the exact same thread to deserializes again and continues execution. Which is quite distinct from marshaling between processes, that has to happen between two distinct threads. With the considerable overhead of marshaling between distinct virtual memory views and the required thread context switch. An AD is a much cheaper version of a process.
我不相信用户线程可以跨越多个应用程序域。然而,CLR 工作线程、GC 线程等将会并且能够做到。
I do not believe a user thread can cut across multiple appDomains. However, CLR worker threads, GC threads and the like will and can do.
一个示例可能是调用本机代码,而本机代码调用另一个应用程序域中的回调。
进程内部的封送可能会使用优化的路由,其中在多个 AppDomain 中使用相同的操作系统线程。
One example could be calling native code and the native code calls a callback in another appdomain.
And marshaling inside a process might use an optimized route where the same OS thread is used in multiple AppDomains.