Web Api - 即发即忘 [英] Web Api - Fire and Forget

查看:33
本文介绍了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() 而没有任何 async-await 吗?

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 或我的 向 ASP.NET 运行时注册您的牛仔背景作品="https://github.com/StephenCleary/AspNetBackgroundTasks" rel="noreferrer">ASP.NET 后台任务库.请注意,QBWI 和 AspNetBackgroundTasks 都是不可靠的解决方案;他们只是尽量减少你失去工作的机会,而不是阻止它.

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天全站免登陆