1. 重构 DeviceManagementService 类:

- 修改 CreateDeviceWithDetailsAsync 方法,在数据库创建成功后自动添加到内存
      - 修改 UpdateDeviceAsync 方法,在数据库更新成功后自动更新内存
      - 修改 DeleteDeviceByIdAsync 方法,在数据库删除成功后自动从内存移除
      - 修改 ToggleDeviceActiveStateAsync 方法,在数据库切换激活状态后更新内存

   2. 更新 DeviceDataService 类:
      - 移除了在 AddDevice 方法中的独立 AddDeviceToMemory 调用
      - 移除了在 DeleteDevice 方法中的独立 RemoveDeviceFromMemory 调用
      - 为 UpdateDevice 方法添加了注释,说明内存自动更新

   3. 更新 DeviceMonitoringService 类:
      - 在 OnDeviceActiveChanged 方法中使用 Task 运行异步的 UpdateDeviceAsync 调用

   4. 更新接口文档:
      - 在 IDeviceManagementService 接口中更新了内存操作方法的注释,说明通常由其他操作自动调用
This commit is contained in:
2025-10-01 18:09:30 +08:00
parent 03e92811dd
commit 2dda2029bd
4 changed files with 45 additions and 9 deletions

View File

@@ -47,7 +47,15 @@ public class DeviceManagementService : IDeviceManagementService
/// </summary>
public async Task<CreateDeviceWithDetailsDto> CreateDeviceWithDetailsAsync(CreateDeviceWithDetailsDto dto)
{
return await _deviceAppService.CreateDeviceWithDetailsAsync(dto);
var result = await _deviceAppService.CreateDeviceWithDetailsAsync(dto);
// 创建成功后,将设备添加到内存中
if (result?.Device != null)
{
AddDeviceToMemory(result.Device);
}
return result;
}
/// <summary>
@@ -55,7 +63,15 @@ public class DeviceManagementService : IDeviceManagementService
/// </summary>
public async Task<int> UpdateDeviceAsync(DeviceDto deviceDto)
{
return await _deviceAppService.UpdateDeviceAsync(deviceDto);
var result = await _deviceAppService.UpdateDeviceAsync(deviceDto);
// 更新成功后,更新内存中的设备
if (result > 0 && deviceDto != null)
{
UpdateDeviceInMemory(deviceDto);
}
return result;
}
/// <summary>
@@ -63,7 +79,16 @@ public class DeviceManagementService : IDeviceManagementService
/// </summary>
public async Task<bool> DeleteDeviceByIdAsync(int deviceId)
{
return await _deviceAppService.DeleteDeviceByIdAsync(deviceId);
var device = await _deviceAppService.GetDeviceByIdAsync(deviceId); // 获取设备信息用于内存删除
var result = await _deviceAppService.DeleteDeviceByIdAsync(deviceId);
// 删除成功后,从内存中移除设备
if (result && device != null)
{
RemoveDeviceFromMemory(deviceId);
}
return result;
}
/// <summary>
@@ -72,6 +97,13 @@ public class DeviceManagementService : IDeviceManagementService
public async Task ToggleDeviceActiveStateAsync(int id)
{
await _deviceAppService.ToggleDeviceActiveStateAsync(id);
// 更新内存中的设备状态
var device = await _deviceAppService.GetDeviceByIdAsync(id);
if (device != null)
{
UpdateDeviceInMemory(device);
}
}
/// <summary>

View File

@@ -40,7 +40,11 @@ public class DeviceMonitoringService : IDeviceMonitoringService, IDisposable
{
if (_appDataStorageService.Devices.TryGetValue(e.DeviceId, out var device))
{
_appDataCenterService.DeviceManagementService.UpdateDeviceAsync(device);
// 更新设备激活状态 - 同时更新数据库和内存
_ = Task.Run(async () =>
{
await _appDataCenterService.DeviceManagementService.UpdateDeviceAsync(device);
});
}
}