问题
I have a method similar to the following in WebAPI - MVC
public IActionResult Post(Model model)
{
ALongRunningMethod();
return Ok();
}
I have two options.
- Wait for the method to complete. But, what if its too long ? Doesn't the API timeout ?
- Run that in a separate thread using
Tasks
but returnOk (200 HTTP Code) immediately
? What if some exception occur in that long running method ?
Totally confused. What should I do in this case ?
回答1:
This is a common issue in web applications. I would create a GUID
, pass it into a task, run the task, pass back the GUID
. In the mean time, the task will continue. If you have a database you could save the GUID
to the DB from the task, indicating some status. e.g. You could have a database table called 'Task' with columns TaskID
and Status
.
Then you can use the GUID
to retrieve (poll) for the status of the task at regular intervals.
The commenter is correct in saying that long-running tasks in ASP.NET is a dangerous game because you have no control over the lifetime of the app domain.
回答2:
Starting from .Net 4.5.2, you now have QueueBackgroundWorkItem to deal with long running operations in ASP.Net.
回答3:
The best way to handle this would be to have a separate service to actually perform the tasks that you want to run as opposed to running them from within your web api controllers.
Have the Web API endpoint write an entry to the database requesting some work to be done and have another separate service read from that table and perform those long running tasks.
You can of course provide some kind of id so that you can query for progress using another end point within your WEB API if you so wish.
The reason for this and the problem you are likely going to run into is that ASP.NET only knows about code running that is associated with a request, the code you are looking to run in a background thread would not be seen as part of a request could therefore be ended at any point for a number of reaons...
Here are some examples of those risks:
- An unhandled exception in a thread not associated with a request will take down the process.
- If you run your site in a Web Farm, you could end up with multiple instances of your app that all attempt to run the same task at the same time.
- The AppDomain your site runs in can go down for a number of reasons and take down your background task with it. This could corrupt data if it happens in the middle of your code execution.
See this page for more information: http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx/
Hope this helps.
来源:https://stackoverflow.com/questions/25971502/long-running-method-in-controller-action-mvc