为什么要使用Thread.CurrentContext属性和Thread.GetDomain()方法?

这不是一个重要的问题,但我想知道为什么Thread类公开了一个属性来获取当前的Context( Thread.CurrentContext )和一个获取当前AppDomain( Thread.GetDomain() )的方法。

知道了Process> AppDomain> Context> Thread的层次结构,我的假设是在当前时间点知道线程的上下文,并且需要根据当前上下文搜索域。

但我想听听更明智的答案。 谢谢!

我的假设是线程的上下文在当前时间点是已知的,并且需要根据当前上下文搜索域。

实际上,在.NET Framework的当前实现中, Context对象保持对其父域的引用 。 框架设计者可能已将上下文的域公开为Thread.Context.Domain 。 这可能是一个修辞问题,为什么他们不这样做; 通过查看参考源代码我无法分辨。

重要的是,在任何给定的时刻,线程都在特定域内执行代码。 这可以是进程的默认域,也可以是通过AppDomain.DoCallBackAppDomain.ExecuteAssembly或编组的MarshalByRefObject -object输入的域。 这将是Thread.GetDomain()返回的域。

此域至少有一个上下文(默认值),但它也可能具有为ContextBoundObject -objects创建的其他上下文。 可以通过Context.DoCallBack在同一个域上显式输入任何这些上下文,也可以通过调用编组的ContextBoundObject -object从任何域隐式输入。 这是Thread.Context返回的上下文

线程和域或线程和上下文之间没有父子关系。 但是,域与其上下文之间存在严格的父子关系,一对多关系。 因此,不需要基于当前上下文搜索域。

如果你喜欢玩它多一点,这里是我使用的应用程序:

 using System; using System.Runtime.Remoting.Contexts; using System.Threading; namespace ConsoleApplication { public class Program { [Synchronization] public class CtxObject : ContextBoundObject { public void Report(string step) { Program.Report(step); } } public static void Main(string[] args) { Program.Report("app start"); System.AppDomain domain = System.AppDomain.CreateDomain("New domain"); var ctxOb = new CtxObject(); ctxOb.Report("ctxOb object"); domain.SetData("ctxOb", ctxOb); domain.DoCallBack(() => { Program.Report("inside another domain"); var ctxOb2 = (CtxObject)System.AppDomain.CurrentDomain.GetData("ctxOb"); ctxOb2.Report("ctxOb called from another domain"); }); Console.ReadLine(); } static void Report(string step) { var threadDomain = Thread.GetDomain().FriendlyName; Console.WriteLine( new { // Thread.CurrentContext.ContextID is only unique for the scope of domain step, ctx = Thread.CurrentContext.GetHashCode(), threadId = Thread.CurrentThread.ManagedThreadId, domain = Thread.GetDomain().FriendlyName, }); } } } 
Interesting Posts