由于CLR维护了托管线程池,使用过的线程并不会立即销毁,在需要的时候会继续复用。在类似ASP.NET PerCall或WCF PerCall条件下,当Call1在线程ManagedThreadId1中处理完毕后,Call2发生,而Call2很有可能也在线程ManagedThreadId1中处理。这种条件下Call2会自动复用处理Call1时生成并缓存的对象实例。
public class PerCallContextLifeTimeManager : LifetimeManager
{
private string _key =
string.Format(CultureInfo.InvariantCulture,
"PerCallContextLifeTimeManager_{0}", Guid.NewGuid());
public override object GetValue()
{
return CallContext.GetData(_key);
}
public override void SetValue(object newValue)
{
CallContext.SetData(_key, newValue);
}
public override void RemoveValue()
{
CallContext.FreeNamedDataSlot(_key);
}
}
private static void TestPerCallContextLifeTimeManager()
{
IExample example;
using (IUnityContainer container = new UnityContainer())
{
container.RegisterType(typeof(IExample), typeof(Example),
new PerCallContextLifeTimeManager());
container.ResolveIExample>().SayHello();
container.ResolveIExample>().SayHello();
Actionint> action = delegate(int sleep)
{
container.ResolveIExample>().SayHello();
Thread.Sleep(sleep);
container.ResolveIExample>().SayHello();
};
Thread thread1 = new Thread((a) => action.Invoke((int)a));
Thread thread2 = new Thread((a) => action.Invoke((int)a));
thread1.Start(50);
thread2.Start(55);
thread1.Join();
thread2.Join();
ThreadPool.QueueUserWorkItem((a) => action.Invoke((int)a), 50);
ThreadPool.QueueUserWorkItem((a) => action.Invoke((int)a), 55);
Thread.Sleep(100);
ThreadPool.QueueUserWorkItem((a) => action.Invoke((int)a), 50);
ThreadPool.QueueUserWorkItem((a) => action.Invoke((int)a), 55);
Thread.Sleep(100);
ThreadPool.QueueUserWorkItem((a) => action.Invoke((int)a), 50);
ThreadPool.QueueUserWorkItem((a) => action.Invoke((int)a), 55);
Thread.Sleep(100);
example = container.ResolveIExample>();
}
example.SayHello();
Console.ReadKey();
}