Web Api-忘却火 [英] Web Api - Fire and Forget

查看:70
本文介绍了Web Api-忘却火的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web API动作,需要运行一些任务,而不必理会该任务. 这是我的方法现在的组织方式:

I have a Web API's action where I need to run some task and forget about this task. This is how my method is organized now:

public async Task<SomeType> DoSth()
{
    await Task.Run(...);
    .....
    //Do some other work
}

问题是,它显然在完成时在等待行处停止,然后才继续工作. 我需要解雇" 我是否应该在没有任何异步等待的情况下仅调用Task.Run()?

The thing is that obviously it stops at the await line waiting when it's done and only then continues the work. And I need to "fire and forget" Should I just call Task.Run() without any async-await?

推荐答案

我需要解雇"

And I need to "fire and forget"

我有一篇博客文章,其中详细介绍了在ASP.NET上一劳永逸.

I have a blog post that goes into details of several different approaches for fire-and-forget on ASP.NET.

总而言之:首先,请尽量不要做一劳永逸的事情.这几乎总是一个坏主意.您真的要忘记"吗?例如,是否在乎是否成功完成?忽略任何错误?接受偶尔的丢失的工作"而没有任何日志通知?几乎总是答案是否定的,一劳永逸"是不合适的方法.

In summary: first, try not to do fire-and-forget at all. It's almost always a bad idea. Do you really want to "forget"? As in, not care whether it completes successfully or not? Ignore any errors? Accept occasional "lost work" without any log notifications? Almost always, the answer is no, fire-and-forget is not the appropriate approach.

可靠的解决方案是构建适当的分布式体系结构.也就是说,构造代表要完成的工作的消息,并将该消息排队到可靠的队列(例如,Azure队列,MSMQ等)中.然后有一个独立的后端来处理该队列(例如,Azure WebJob,Win32服务等).

A reliable solution is to build a proper distributed architecture. That is, construct a message that represents the work to be done and queue that message to a reliable queue (e.g., Azure Queue, MSMQ, etc). Then have an independent backend that process that queue (e.g., Azure WebJob, Win32 service, etc).

我应该在没有任何异步等待的情况下直接调用Task.Run()吗?

Should I just call Task.Run() without any async-await?

不.这是最糟糕的解决方案.如果您必须一劳永逸",而又不想构建分布式体系结构,请考虑使用"Hangfire".如果这对您不起作用,则至少应非常通过HostingEnvironment.QueueBackgroundWorkItem或我的

No. This is the worst possible solution. If you must do fire-and-forget, and you're not willing to build a distributed architecture, then consider Hangfire. If that doesn't work for you, then at the very least you should register your cowboy background work with the ASP.NET runtime via HostingEnvironment.QueueBackgroundWorkItem or my ASP.NET Background Tasks library. Note that QBWI and AspNetBackgroundTasks are both unreliable solutions; they just minimize the chance that you'll lose work, not prevent it.

这篇关于Web Api-忘却火的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆