由于CLR維護(hù)了托管線程池,使用過的線程并不會立即銷毀,在需要的時候會繼續(xù)復(fù)用。在類似ASP.NET PerCall或WCF PerCall條件下,當(dāng)Call1在線程ManagedThreadId1中處理完畢后,Call2發(fā)生,而Call2很有可能也在線程ManagedThreadId1中處理。這種條件下Call2會自動復(fù)用處理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();
}