I'm creating an ASP.NET Core WebApi, which uses the Autodesk Model Derivative API to convert a Revit file into another file format. After I've uploaded the file, the Autodesk API starts working in the background and can take several minutes to finish its work.
I want to monitor the status of the Autodesk API, to know if the conversion has been finished yet and notify the user. I'm looking for the best way to monitor the status of the job without 'awaiting' and letting the request hang stuck for several minutes.
I've tried just running the task asynchronously without awaiting the result. This worked, up to the point where I wanted to update a value in my Database Context, because that had been disposed due to the request having ended.
I've also researched several options on implementing background services, but haven't found a clear way to do that.
public async Task<ActionResult<Response<JobResponse>>> UploadFile(string bucketKey, IFormFile file)
{
// ....
// File has been uploaded
Response<JobResponse> response
= await NetworkManager.PostAsync<JobResponse>(URI.Job.Url, JsonConvert.SerializeObject(jobData));
// The job has been created in the Autodesk API, so I create a record in my own database
var job = new Job(urn, file.FileName);
context.Jobs.Add(job);
await context.SaveChangesAsync();
// This method is what I want to do in the background
MonitorStatus(job);
return Respond(response);
}
private async Task MonitorStatus(Job job)
{
bool isDone = false;
while (!isDone)
{
isDone = await IsDone(job.Urn);
if (!isDone)
await Task.Delay(10000);
}
string guid = await new JobRepository(job).GetGuid();
// The line underneath throws an error because the context has been disposed
(await context.Jobs.FindAsync(job.Id)).Finish(guid);
await context.SaveChangesAsync();
// ...
// Notify the user
}
Translation of files in Model Derivative API boils down to two main endpoints:
If you're making the HTTP requests yourself, you can just poll the manifest until you see that the translation has been completed.
If you're using the Forge .NET SDK, you can trigger the translation using the Translate method, and poll the results using the GetManifest method.