Skip to content

Commit

Permalink
improve refcount debug code
Browse files Browse the repository at this point in the history
  • Loading branch information
RevenantX committed May 16, 2021
1 parent 30e86ce commit e96bb61
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 16 deletions.
2 changes: 1 addition & 1 deletion LiteNetLib/NetPacket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public ushort FragmentsTotal
public NetPacket Next;

#if DEBUG_REFCOUNT
public int RefCount = 0;
public int RefCount = 1;
#endif

public NetPacket(int size)
Expand Down
26 changes: 11 additions & 15 deletions LiteNetLib/NetPacketPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public NetPacket GetWithProperty(PacketProperty property)

public NetPacket GetPacket(int size)
{
if (size > NetConstants.MaxPacketSize)
if (size > NetConstants.MaxPacketSize)
return new NetPacket(size);

NetPacket packet;
Expand All @@ -46,15 +46,10 @@ public NetPacket GetPacket(int size)
} while (packet != Interlocked.CompareExchange(ref _head, packet.Next, packet));

#if DEBUG_REFCOUNT
if (Interlocked.Increment(ref packet.RefCount) > 1)
{
Interlocked.Decrement(ref packet.RefCount);
NetDebug.WriteError("PacketRefCount more than 1: {0}", Environment.StackTrace);
return new NetPacket(size);
}
Interlocked.Increment(ref packet.RefCount);
#endif

_count--;
Interlocked.Decrement(ref _count);
packet.Size = size;
if (packet.RawData.Length < size)
packet.RawData = new byte[size];
Expand All @@ -69,20 +64,21 @@ public void Recycle(NetPacket packet)
return;
}

_count++;
#if DEBUG_REFCOUNT
int result = Interlocked.Decrement(ref packet.RefCount);
if (result != 0)
NetDebug.WriteError("PacketRefCount invalid: {0}, {1}", result, Environment.StackTrace);
#endif

Interlocked.Increment(ref _count);

//Clean fragmented flag
packet.RawData[0] = 0;

#if DEBUG_REFCOUNT
if (packet.RefCount > 0)
Interlocked.Decrement(ref packet.RefCount);
#endif

do
{
packet.Next = _head;
} while (packet.Next != Interlocked.CompareExchange(ref _head, packet, packet.Next));
}
}
}
}

0 comments on commit e96bb61

Please sign in to comment.