国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

基于自定義Unity生存期模型PerCallContextLifeTimeManager的問題

2024-07-10 12:45:43
字體:
來源:轉載
供稿:網友

PerThreadLifetimeManager的問題
使用Unity內置的PerThreadLifetimeManager生存期模型時,其基于ThreadStatic的TLS(Thread Local Storage)設計,也就是說對于每個托管的ManagedThreadId,其會緩存已生成的對象實例。

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

如果我們希望每次調用(PerCall)都生成專用的對象實例,則PerThreadLifetimeManager在此種場景下不適合。

解決辦法有兩種:

1.繼續使用PerThreadLifetimeManager模型,不適用ThreadPool,而手動創建和銷毀線程。
2.自定義對象生存期模型
PerCallContextLifeTimeManager
代碼如下:
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.Resolve<IExample>().SayHello();
        container.Resolve<IExample>().SayHello();

        Action<int> action = delegate(int sleep)
        {
          container.Resolve<IExample>().SayHello();
          Thread.Sleep(sleep);

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南华县| 黔西| 天津市| 卓资县| 霸州市| 华亭县| 从江县| 富阳市| 宁明县| 竹溪县| 广河县| 察雅县| 延安市| 海晏县| 得荣县| 淳安县| 大同市| 合山市| 神池县| 乌恰县| 城口县| 辰溪县| 咸宁市| 娱乐| 赤水市| 中江县| 祥云县| 渝中区| 抚顺市| 古田县| 新宁县| 罗江县| 资溪县| 图们市| 屏东市| 平湖市| 清涧县| 铁岭县| 昆山市| 乌恰县| 霍城县|