Exemplo n.º 1
0
        /// <summary>线程安全</summary>
        public async Task <BaseComponent> GetComponent(Type compType)
        {
            //当comp已激活,且肯定不满足回收条件时可以不用入lifeactor线程
            var   now       = DateTime.Now;
            float threshold = Settings.Ins.CompRecycleTime * 0.67f;//0.67 ~= 2/3

            if (activeTimeMap.TryGetValue(compType, out var activeTime) &&
                (now - activeTime).TotalMinutes < threshold &&
                activeCompMap.TryGetValue(compType, out var retComp))
            {
                activeTimeMap[compType] = DateTime.Now;
                return(retComp);
            }

            //comp的active不一定在所属actor线程执行,谁来获取就在谁的线程执行
            return(await owner.GetLifeActor(compType).SendAsync(async() =>
            {
                activeCompMap.TryGetValue(compType, out var retComp);
                if (retComp == null)
                {
                    retComp = ComponentMgr.Singleton.NewComponent(owner, compType);
                    activeCompMap.TryAdd(compType, retComp);
                }
                if (!retComp.IsActive)
                {
                    await retComp.Active();
                    if (retComp.GetAgent() != null)
                    {
                        await retComp.GetAgent().Active();
                    }
                }
                activeTimeMap[compType] = DateTime.Now;
                return retComp;
            }));
        }