Explorar o código

UPoller增加eNetEventCache,能大大降低CPU和内存消耗

tanghai %!s(int64=11) %!d(string=hai) anos
pai
achega
d19bddd2c6
Modificáronse 2 ficheiros con 17 adicións e 45 borrados
  1. 6 41
      CSharp/Platform/UNet/UAddress.cs
  2. 11 4
      CSharp/Platform/UNet/UPoller.cs

+ 6 - 41
CSharp/Platform/UNet/UAddress.cs

@@ -5,49 +5,14 @@ namespace UNet
 {
 	internal struct UAddress
 	{
-		private uint ip;
-		private ushort port;
+		private readonly uint ip;
+		private readonly ushort port;
 
-		public uint IP
+		public UAddress(string host, int port)
 		{
-			get
-			{
-				return this.ip;
-			}
-			set
-			{
-				this.ip = value;
-			}
-		}
-
-		public ushort Port
-		{
-			get
-			{
-				return this.port;
-			}
-			set
-			{
-				this.port = value;
-			}
-		}
-
-		public string Host
-		{
-			get
-			{
-				IPHostEntry hostInfo = Dns.GetHostEntry(new IPAddress(this.ip));
-				return hostInfo.HostName;
-			}
-			set
-			{
-				IPAddress[] addresslist = Dns.GetHostAddresses(value);
-				foreach (IPAddress address in addresslist)
-				{
-					this.ip = BitConverter.ToUInt32(address.GetAddressBytes(), 0);
-					return;
-				}
-			}
+			IPAddress address = IPAddress.Parse(host);
+			this.ip = BitConverter.ToUInt32(address.GetAddressBytes(), 0);
+			this.port = (ushort) port;
 		}
 
 		public ENetAddress Struct

+ 11 - 4
CSharp/Platform/UNet/UPoller.cs

@@ -23,9 +23,11 @@ namespace UNet
 
 		private readonly BlockingCollection<Action> blockingCollection = new BlockingCollection<Action>();
 
+		private ENetEvent eNetEventCache;
+
 		public UPoller(string hostName, ushort port)
 		{
-			UAddress address = new UAddress { Host = hostName, Port = port };
+			UAddress address = new UAddress(hostName, port);
 			ENetAddress nativeAddress = address.Struct;
 			this.host = NativeMethods.EnetHostCreate(
 				ref nativeAddress, NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID, 0, 0, 0);
@@ -113,7 +115,7 @@ namespace UNet
 		public Task<USocket> ConnectAsync(string hostName, ushort port)
 		{
 			var tcs = new TaskCompletionSource<USocket>();
-			UAddress address = new UAddress { Host = hostName, Port = port };
+			UAddress address = new UAddress(hostName, port);
 			ENetAddress nativeAddress = address.Struct;
 			
 			IntPtr ptr = NativeMethods.EnetHostConnect(
@@ -137,11 +139,16 @@ namespace UNet
 
 		private ENetEvent GetEvent()
 		{
-			ENetEvent eNetEvent = new ENetEvent();
-			if (NativeMethods.EnetHostCheckEvents(this.host, eNetEvent) <= 0)
+			if (this.eNetEventCache == null)
+			{
+				this.eNetEventCache = new ENetEvent();
+			}
+			if (NativeMethods.EnetHostCheckEvents(this.host, this.eNetEventCache) <= 0)
 			{
 				return null;
 			}
+			ENetEvent eNetEvent = this.eNetEventCache;
+			this.eNetEventCache = null;
 			return eNetEvent;
 		}