gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:04:35 25 4
gpt4 key购买 nike

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

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

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

最佳答案

my assumption would be that the context for thread is known at current point in time, and the domain needs to be searched based on current context.

确实,在 .NET Framework 的当前实现中,Context 对象 keeps a reference到其父域。框架设计者可能将上下文的域公开为 Thread.Context.Domain。他们为什么不这样做可能是一个修辞问题;我无法通过查看引用源代码来判断这一点。

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

这个域至少有一个上下文(默认的),但它也可能有其他上下文,为 ContextBoundObject 对象创建。可以通过 Context.DoCallBack 在同一域中显式输入任何这些上下文,或者通过调用编码的 ContextBoundObject 对象从任何域隐式输入这些上下文。 这将是 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,
});
}
}
}

关于c# - 为什么使用 Thread.CurrentContext 属性和 Thread.GetDomain() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22757273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com