Selaa lähdekoodia

EntityRef改成使用WeakReference,之前的实现是强引用,会导致entity无法gc

tanghai 2 vuotta sitten
vanhempi
commit
6bae4b2023
1 muutettua tiedostoa jossa 17 lisäystä ja 7 poistoa
  1. 17 7
      Unity/Assets/Scripts/Core/VProcess/Module/Entity/EntityRef.cs

+ 17 - 7
Unity/Assets/Scripts/Core/VProcess/Module/Entity/EntityRef.cs

@@ -2,30 +2,40 @@ using System;
 
 namespace ET
 {
-    public readonly struct EntityRef<T> where T: Entity
+    public struct EntityRef<T> where T: Entity
     {
-        private readonly long instanceId;
-        private readonly T entity;
+        private long instanceId;
+        // 使用WeakReference,这样不会导致entity dispose了却无法gc的问题
+        // 不过暂时没有测试WeakReference的性能
+        private readonly WeakReference<T> weakRef;
 
         private EntityRef(T t)
         {
             this.instanceId = t.InstanceId;
-            this.entity = t;
+            this.weakRef = new WeakReference<T>(t);
         }
         
         private T UnWrap
         {
             get
             {
-                if (this.entity == null)
+                if (this.instanceId == 0)
                 {
                     return null;
                 }
-                if (this.entity.InstanceId != this.instanceId)
+
+                if (!this.weakRef.TryGetTarget(out T entity))
+                {
+                    this.instanceId = 0;
+                    return null;
+                }
+
+                if (entity.InstanceId != this.instanceId)
                 {
+                    this.instanceId = 0;
                     return null;
                 }
-                return this.entity;
+                return entity;
             }
         }