上下文提供了:
1、一个由一组属性组成的环境,驻留在同一上下文中的所有对象可以共享该环境。
2、一个拦截边界,由运行库对所有来自上下文外的方法调用进行预处理和事后处理。
3、可以保存具有类似运行库要求的对象,如同步、线程亲缘性或即时激活。
---------------------------------------------------------------------------------------------------
Context Agile对象:当运行库创建对象时,会调查对象的上下文请求,以将它放到合适的上下文中。如果没有合适
的上下文,运行时就会创建一个上下文,即默认上下文。大多数对象都会建立在默认上下文中,
这些对象称为Context Agile对象,因为可以直接从应用程序域内的任何地方直接访问它们。
Context Bound对象:确实具有上下文要求的对象称之,它们必须要从 ContextBoundObject 类中派生而来。对该类
对象的跨上下文访问,由模拟实际对象的由运行库生成的代理来提供。代理允许运行库截取跨上
下文调用并可以应用任何预处理和事后处理。(会引起系统开销,慎重使用)
例子:
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Contexts;
namespace ContextTest
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
[Synchronization]
public class MyContextBoundClass: ContextBoundObject
{
}
public class MyAgilClass
{
}
class ContextTest
{
static void Main(string[] args)
{
MyContextBoundClass myBound = new MyContextBoundClass();
MyAgilClass myAgile = new MyAgilClass();
Console.WriteLine("Is myBound out of context?
{0}",RemotingServices.IsObjectOutOfContext(myBound));
Console.WriteLine("Is myAgile out of context?
{0}",RemotingServices.IsObjectOutOfContext(myAgile));
Console.WriteLine("Is myBound a proxy ?
{0}",RemotingServices.IsTransparentProxy(myBound));
Console.WriteLine("Is myAgile a proxy ?
{0}",RemotingServices.IsTransparentProxy(myAgile));
Console.ReadLine();
}
}
}
运行结果:
Is myBound out of context? true
Is myAgile out of context? false
Is myBound a proxy ? true
Is myAgile a proxy ? false
***************************************************************************
利用 Thread.CurrentContext 静态方法,您可以获取对当前正在执行的上下文的引用。所返回的 Context 对象可用来查找与上下文相关的各种信息。