J'ai travaillé avec des méthodes asynchrones et des méthodes qui renvoient plusieurs valeurs séparément. Dans cette situation spécifique, la méthode "GetTaskTypeAndId ()" suivante doit être asynchrone et doit renvoyer plusieurs valeurs en même temps. Comment dois-je rendre cette méthode asynchrone?
public async Task DeleteSchoolTask(int schoolNumber, int taskDetailId)
{
var result = GetTaskTypeAndId(taskDetailId); // This should be called asynchronously
int taskId = result.Item1;
string taskType = result.Item2;
// step 1: delete attachment physically from server
var fileService = new FileService(Logger, CurrentUser);
var relativeFilePath = $"{schoolNumber}\\{Consts.RM_SCHOOL}\\{taskDetailId}";
fileService.DeleteAttachmentFolderFromServer(Consts.CONFIG_SMP_UPLOADFILE_ROOTPATH, relativeFilePath);
// step 2: delete records from database
await _routineMaintenanceRepo.Value.DeleteSchoolTask(taskDetailId);
}
public (int, string) GetTaskTypeAndId(int taskDetailId) // How should I write this line using 'async Task'?
{
var detailRecord = await _routineMaintenanceRepo.Value.GetDetailRecord(taskDetailId);
int taskId = 0;
string taskType = "";
switch (detailRecord.TaskType)
{
case 1:
taskId = (int)detailRecord.RoutineMaintenanceTaskId;
taskType = Consts.RM_DEFAULT;
break;
case 2:
taskId = (int)detailRecord.RoutineMaintenanceTaskDuplicateId;
taskType = Consts.RM_DUPLICATE;
break;
case 3:
taskId = (int)detailRecord.RoutineMaintenanceTaskSchoolId;
taskType = Consts.RM_SCHOOL;
break;
default:
break;
}
return (taskId, taskType);
}
Après avoir joué avec le code, j'ai pu le comprendre. Voici la solution.
public async Task DeleteSchoolTask(int schoolNumber, int taskDetailId)
{
var result = await GetTaskTypeAndId(taskDetailId);
int taskId = result.Item1;
string taskType = result.Item2;
// step 1: delete attachment physically from server
var fileService = new FileService(Logger, CurrentUser);
var relativeFilePath = $"{schoolNumber}\\{Consts.RM_SCHOOL}\\{taskDetailId}";
fileService.DeleteAttachmentFolderFromServer(Consts.CONFIG_SMP_UPLOADFILE_ROOTPATH, relativeFilePath);
// step 2: delete records from database
await _routineMaintenanceRepo.Value.DeleteSchoolTask(taskDetailId);
}
public async Task<(int, string)> GetTaskTypeAndId(int taskDetailId)
{
var detailRecord = await _routineMaintenanceRepo.Value.GetDetailRecord(taskDetailId);
int taskId = 0;
string taskType = "";
switch (detailRecord.TaskType)
{
case 1:
taskId = (int)detailRecord.RoutineMaintenanceTaskId;
taskType = Consts.RM_DEFAULT;
break;
case 2:
taskId = (int)detailRecord.RoutineMaintenanceTaskDuplicateId;
taskType = Consts.RM_DUPLICATE;
break;
case 3:
taskId = (int)detailRecord.RoutineMaintenanceTaskSchoolId;
taskType = Consts.RM_SCHOOL;
break;
default:
break;
}
return (taskId, taskType);
}