如何回答请求但继续在WebApi中处理代码 [英] How to answer a request but continue processing code in WebApi
问题描述
我想回答一个请求,但继续处理代码.
I would like to answer a request, but continue processing code.
我尝试过类似的事情:
[HttpPost]
public async Task<HttpResponseMessage> SendAsync(MyRequest sms)
{
await Task.Run(() => Process(sms)); //need to run in a separate thread
var response = new MyRequest(sms) { Ack = true };
return Request.CreateResponse(HttpStatusCode.Created, response.ToString());
}
private async void Process(MyRequest sms)
{
var validationResult = new MyRequestValidation(_p2pContext, _carrierService).Validate(sms);
if (string.IsNullOrWhiteSpace(validationResult.Errors[0].PropertyName)) // Request not valid
return;
Message msg;
if (validationResult.IsValid)
{
msg = await _messageService.ProcessAsync(sms);
}
else // Create message as finished
{
msg = _messageService.MessageFromMyRequest(sms,
finished: true,
withEventSource: validationResult.Errors[0].CustomState.ToString()
);
}
// Salve in db
_p2pContext.MessageRepository.Create(msg);
_p2pContext.Save();
}
推荐答案
我想回答一个请求,但继续处理代码.
I would like to answer a request, but continue processing code.
您确定要在ASP.NET中执行此操作吗?这不是ASP.NET(或任何Web服务器)旨在处理的情况.
Are you sure you want to do this in ASP.NET? This is not a situation that ASP.NET (or any web server) was designed to handle.
执行此操作的经典(正确)方法是将工作排队到持久队列中,并有一个单独的后端进程来完成该工作的实际处理.
The classic (correct) way to do this is to queue the work to a persistent queue and have a separate backend process do the actual processing of that work.
在请求上下文之外的ASP.NET内部进行处理存在各种危险.通常,您不能假设该工作会真正完成.如果您对此表示满意(或只是想过着危险的生活),则可以使用HostingEnvironment.QueueBackgroundWorkItem
.
There are all kinds of dangers with doing processing inside of ASP.NET outside of a request context. In general, you can't assume that the work will ever actually be done. If you're OK with that (or just like to live dangerously), then you can use HostingEnvironment.QueueBackgroundWorkItem
.
我有一个博客帖子会更加详细.
这篇关于如何回答请求但继续在WebApi中处理代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!