First of all I have to say that I'm not sure if I'm coding the proper approach, I'll first explain what I'm trying to do.
- Receive POST request to create a new RawTask.
- Insert the RawTask in its DB table and a related register in ProcessedTask table.
- Execute some long tasks (inside Thread.Task)
- Update the ProcessedTask with the feedback of the previous point.
Doubts/Problems
- The first problem is that the DBContext doesn't exist when the task finishes its execution. So it's impossible to update the processedTask.
- The insertedTask.ExecuteScript() is well placed at TaskController/POST method?
- Is it a good approach to create and update the ProcessedTask entity in the POST method of this Task Controller?
Here's some code to explain it better.
public class RawTaskController : ControllerBase
{
private readonly ICrudService<RawTask> _rawTaskCrudService;
private readonly ICrudService<ProcessedTask> _processedTaskCrudService;
public RawTaskController(ICrudService<RawTask> taskCrudService, ICrudService<ProcessedTask> processedTaskCrudService)
{
_rawTaskCrudService = taskCrudService;
_processedTaskCrudService = processedTaskCrudService;
}
[HttpPost]
public async Task<IActionResult> AddTask([FromBody] RawTaskModel rawTask)
{
insertedRawTask insertedRawTask;
ProcessedTask processedTask = new ProcessedTask();
try
{
//Initialize some fields
rawTask.Id = Guid.NewGuid();
rawTask.DateReg = DateTime.Now;
//Insert the received task after mapping the model.
insertedRawTask = await _rawTaskCrudService.Add(rawTaskMapper.Map(rawTask));
if (insertedRawTask != null)
{
//Initializing the new processedTask
processedTask.Id = Guid.NewGuid();
processedTask.IdRawTask = insertedRawTask.Id;
processedTask.DateReg = DateTime.Now;
}
//Insert the processedTask after getting some fields from RawTask.
ProcessedTask insertedProcessedTask = await _processedTaskCrudService.Add(processedTask);
if (insertedProcessedTask != null)
{
//Here comes the long executiong, for example a HDD defrag (some hours)
Task task = new Task(async () =>
{
//The behaviour of the execution is defined in the domain class Task
if (insertedRawTask.ExecuteScript())
{
//If the execution was succesful we will update the processedTask created before
insertedProcessedTask.State = "Finished";
await _processedTaskCrudService.Update(insertedProcessedTask);
}
});
task.Start();
}
else
{
return StatusCode(500);
}
}
catch (Exception)
{
return StatusCode(500);
}
return Ok(insertedRawTask);
}
}
I would appreciate any other possible solutions to accomplish this kind of behavior.
Thanks in advance.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…