fix: 使用互斥锁确保数据写入的顺序性

This commit is contained in:
SikongJueluo 2025-07-14 17:13:53 +08:00
parent c9fc6961fa
commit 6500c1ce2d
No known key found for this signature in database
1 changed files with 19 additions and 15 deletions

View File

@ -346,25 +346,28 @@ public class UDPServer
return retPack.Value;
}
private void ReceiveHandler(byte[] data, IPEndPoint endPoint)
private async Task ReceiveHandler(byte[] data, IPEndPoint endPoint, DateTime time)
{
// Handle RemoteEP
if (endPoint is null)
// 异步锁保护 udpData
await Task.Run(() =>
{
logger.Debug($"Receive Data from Unknown at {DateTime.Now.ToString()}:");
logger.Debug($" Original Data : {BitConverter.ToString(data).Replace("-", " ")}");
return;
}
lock (udpData)
{
// Handle RemoteEP
if (endPoint is null)
{
logger.Debug($"Receive Data from Unknown at {DateTime.Now.ToString()}:");
logger.Debug($" Original Data : {BitConverter.ToString(data).Replace("-", " ")}");
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;
}
}