fix: 使用互斥锁确保数据写入的顺序性
This commit is contained in:
parent
c9fc6961fa
commit
6500c1ce2d
|
@ -346,7 +346,12 @@ public class UDPServer
|
|||
return retPack.Value;
|
||||
}
|
||||
|
||||
private void ReceiveHandler(byte[] data, IPEndPoint endPoint)
|
||||
private async Task ReceiveHandler(byte[] data, IPEndPoint endPoint, DateTime time)
|
||||
{
|
||||
// 异步锁保护 udpData
|
||||
await Task.Run(() =>
|
||||
{
|
||||
lock (udpData)
|
||||
{
|
||||
// Handle RemoteEP
|
||||
if (endPoint is null)
|
||||
|
@ -356,15 +361,13 @@ public class UDPServer
|
|||
return;
|
||||
}
|
||||
|
||||
// 异步处理数据包
|
||||
Task.Run(() =>
|
||||
{
|
||||
var udpData = RecordUDPData(data, endPoint, Convert.ToInt32(data[1]));
|
||||
PrintData(udpData);
|
||||
var udpDataObj = RecordUDPData(data, endPoint, time, Convert.ToInt32(data[1]));
|
||||
PrintData(udpDataObj);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private UDPData RecordUDPData(byte[] bytes, IPEndPoint remoteEP, int taskID)
|
||||
private UDPData RecordUDPData(byte[] bytes, IPEndPoint remoteEP, DateTime time, int taskID)
|
||||
{
|
||||
var remoteAddress = remoteEP.Address.ToString();
|
||||
var remotePort = remoteEP.Port;
|
||||
|
@ -374,7 +377,7 @@ public class UDPServer
|
|||
Port = remotePort,
|
||||
TaskID = taskID,
|
||||
Data = bytes,
|
||||
DateTime = DateTime.Now,
|
||||
DateTime = time,
|
||||
HasRead = false,
|
||||
};
|
||||
|
||||
|
@ -482,7 +485,7 @@ public class UDPServer
|
|||
try
|
||||
{
|
||||
UdpReceiveResult result = await client.ReceiveAsync();
|
||||
ReceiveHandler(result.Buffer, result.RemoteEndPoint);
|
||||
ReceiveHandler(result.Buffer, result.RemoteEndPoint, DateTime.Now);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
@ -510,6 +513,7 @@ public class UDPServer
|
|||
item.Close();
|
||||
}
|
||||
this.isRunning = false;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue