日韩天天综合网_野战两个奶头被亲到高潮_亚洲日韩欧美精品综合_av女人天堂污污污_视频一区**字幕无弹窗_国产亚洲欧美小视频_国内性爱精品在线免费视频_国产一级电影在线播放_日韩欧美内地福利_亚洲一二三不卡片区

基于自定義Unity生存期模型PerCallContextLifeTimeManager的問(wèn)題_.Net教程

編輯Tag賺U幣

推薦:asp.net C#實(shí)現(xiàn)下載文件的六種方法實(shí)例
asp.net C#實(shí)現(xiàn)下載文件的六種方法實(shí)例,需要的朋友可以參考一下

PerThreadLifetimeManager的問(wèn)題
使用Unity內(nèi)置的PerThreadLifetimeManager生存期模型時(shí),其基于ThreadStatic的TLS(Thread Local Storage)設(shè)計(jì),也就是說(shuō)對(duì)于每個(gè)托管的ManagedThreadId,其會(huì)緩存已生成的對(duì)象實(shí)例。

由于CLR維護(hù)了托管線程池,使用過(guò)的線程并不會(huì)立即銷毀,在需要的時(shí)候會(huì)繼續(xù)復(fù)用。在類似ASP.NET PerCall或WCF PerCall條件下,當(dāng)Call1在線程ManagedThreadId1中處理完畢后,Call2發(fā)生,而Call2很有可能也在線程ManagedThreadId1中處理。這種條件下Call2會(huì)自動(dòng)復(fù)用處理Call1時(shí)生成并緩存的對(duì)象實(shí)例。

如果我們希望每次調(diào)用(PerCall)都生成專用的對(duì)象實(shí)例,則PerThreadLifetimeManager在此種場(chǎng)景下不適合。

解決辦法有兩種:

1.繼續(xù)使用PerThreadLifetimeManager模型,不適用ThreadPool,而手動(dòng)創(chuàng)建和銷毀線程。
2.自定義對(duì)象生存期模型
PerCallContextLifeTimeManager

復(fù)制代碼 代碼如下:hl5o.cn

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);
}
}


使用舉例
復(fù)制代碼 代碼如下:hl5o.cn

private static void TestPerCallContextLifeTimeManager()
{
IExample example;
using (IUnityContainer container = new UnityContainer())
{
container.RegisterType(typeof(IExample), typeof(Example),
new PerCallContextLifeTimeManager());

container.Resolve<IExample>().SayHello();
container.Resolve<IExample>().SayHello();

Action<int> action = delegate(int sleep)
{
container.Resolve<IExample>().SayHello();
Thread.Sleep(sleep);
container.Resolve<IExample>().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.Resolve<IExample>();
}

example.SayHello();

Console.ReadKey();
}

分享:基于Unity容器中的對(duì)象生存期管理分析
基于Unity容器中的對(duì)象生存期管理分析

來(lái)源:模板無(wú)憂//所屬分類:.Net教程/更新時(shí)間:2013-04-22
相關(guān).Net教程