瀏覽代碼

用Task.FromResult简化了代码

tanghai 8 年之前
父節點
當前提交
41d3bd6f91

+ 5 - 7
Server/Base/Network/TNet/TChannel.cs

@@ -231,17 +231,15 @@ namespace Base
 			{
 				throw new Exception("TChannel已经被Dispose, 不能接收消息");
 			}
-			TaskCompletionSource<byte[]> tcs = new TaskCompletionSource<byte[]>();
+			
 			byte[] packet = this.parser.GetPacket();
 			if (packet != null)
 			{
-				tcs.SetResult(packet);
-			}
-			else
-			{
-				recvTcs = tcs;
+				return Task.FromResult(packet);
 			}
-			return tcs.Task;
+			
+			recvTcs = new TaskCompletionSource<byte[]>();
+			return recvTcs.Task;
 		}
 	}
 }

+ 5 - 8
Server/Base/Network/UNet/UChannel.cs

@@ -79,18 +79,15 @@ namespace Base
 			{
 				throw new Exception("UChannel已经被Dispose, 不能接收消息");
 			}
-			TaskCompletionSource<byte[]> tcs = new TaskCompletionSource<byte[]>();
+			
 			var recvQueue = this.socket.RecvQueue;
 			if (recvQueue.Count > 0)
 			{
-				tcs.SetResult(recvQueue.Dequeue());
-			}
-			else
-			{
-				recvTcs = tcs;
+				return Task.FromResult(recvQueue.Dequeue());
 			}
-			
-			return tcs.Task;
+
+			recvTcs = new TaskCompletionSource<byte[]>();
+			return recvTcs.Task;
 		}
 
 		private void OnRecv()

+ 5 - 9
Server/Base/Network/UNet/UPoller.cs

@@ -102,9 +102,7 @@ namespace Base
 			{
 				throw new Exception("do not accept twice!");
 			}
-
-			var tcs = new TaskCompletionSource<USocket>();
-
+			
 			// 如果有请求连接缓存的包,从缓存中取
 			if (this.connQueue.Count > 0)
 			{
@@ -112,13 +110,11 @@ namespace Base
 
 				USocket socket = new USocket(ptr, this);
 				this.USocketManager.Add(ptr, socket);
-				tcs.SetResult(socket);
+				return Task.FromResult(socket);
 			}
-			else
-			{
-				this.AcceptTcs = tcs;
-			}
-			return tcs.Task;
+
+			this.AcceptTcs = new TaskCompletionSource<USocket>();
+			return this.AcceptTcs.Task;
 		}
 
 		private void OnAccepted(ENetEvent eEvent)

+ 2 - 3
Server/Model/Component/Unit/LockComponent.cs

@@ -67,13 +67,12 @@ namespace Model
 
 		private Task<bool> WaitLock()
 		{
-			TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
 			if (this.status == LockStatus.Locked)
 			{
-				tcs.SetResult(true);
-				return tcs.Task;
+				return Task.FromResult(true);
 			}
 
+			TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
 			this.queue.Enqueue(tcs);
 			return tcs.Task;
 		}

+ 5 - 8
Server/Model/Component/Unit/MasterComponent.cs

@@ -39,18 +39,15 @@ namespace Model
 
 		public Task<bool> Lock(string address)
 		{
-			TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
-			
 			if (this.lockedAddress == "")
 			{
 				this.lockedAddress = address;
-				tcs.SetResult(true);
-			}
-			else
-			{
-				LockInfo lockInfo = new LockInfo(address, tcs);
-				this.queue.Enqueue(lockInfo);
+				return Task.FromResult(true);
 			}
+
+			TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
+			LockInfo lockInfo = new LockInfo(address, tcs);
+			this.queue.Enqueue(lockInfo);
 			return tcs.Task;
 		}