首页 > 编程语言 > 详细

Unity创建实例:普通实例,单例,线程单例

时间:2020-02-05 17:11:07      阅读:64      评论:0      收藏:0      [点我收藏+]

//Unity容器,默认情况下生成普通对象
//在注册时传入参数new ContainerControlledLifetimeManager(),可以创建单例对象
//在注册的时候传入参数new PerThreadLifetimeManager(),可以创建线程但离对象
//容器不知可以生成对象,还可以管理对象的生命周期
IUnityContainer ucontainer = new UnityContainer();//ContainerControlledLifetimeManager
ucontainer.RegisterType<IPhone, ApplePhone>(new ContainerControlledLifetimeManager());
//单例是只要通过容器生成的对象都是同一个实例,在系统中不同地方获取的单利都是同一个实例
IPhone phone1 = ucontainer.Resolve<IPhone>();
IPhone phone2 = ucontainer.Resolve<IPhone>();
Console.WriteLine($"{object.ReferenceEquals(phone1, phone2)}");

 

//线程单例:同一个线程就是同一个实例,不同线程就是不同的实例
IPhone phone1 = null;
IPhone phone2 = null;
IPhone phone3 = null;
IPhone phone4 = null;
IPhone phone5 = null;
IUnityContainer ucontainer = new UnityContainer();
ucontainer.RegisterType<IPhone, AndroidPhone>(new PerThreadLifetimeManager());
phone1 = ucontainer.Resolve<IPhone>();
phone2 = ucontainer.Resolve<IPhone>();
Console.WriteLine($"12的当前线程ID:{Thread.CurrentThread.ManagedThreadId}");

new Action(() =>
{
phone3 = ucontainer.Resolve<IPhone>();
Console.WriteLine($"3的当前线程ID:{Thread.CurrentThread.ManagedThreadId}");
}).BeginInvoke(null, null);

new Action(() =>
{
phone4 = ucontainer.Resolve<IPhone>();
Console.WriteLine($"4的当前线程ID:{Thread.CurrentThread.ManagedThreadId}");
}).BeginInvoke(arg =>
{
phone5 = ucontainer.Resolve<IPhone>();
Console.WriteLine($"5的当前线程ID:{Thread.CurrentThread.ManagedThreadId}");
}, null);
Thread.Sleep(5000);
Console.WriteLine($"12:{object.ReferenceEquals(phone1, phone2)}");
Console.WriteLine($"13:{object.ReferenceEquals(phone1, phone3)}");
Console.WriteLine($"14:{object.ReferenceEquals(phone1, phone4)}");
Console.WriteLine($"34:{object.ReferenceEquals(phone3, phone4)}");
Console.WriteLine($"45:{object.ReferenceEquals(phone4, phone5)}");

Unity创建实例:普通实例,单例,线程单例

原文:https://www.cnblogs.com/fblogs/p/12263436.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!