您是否需要等待异步方法? [英] Do you have to await async methods?

查看:47
本文介绍了您是否需要等待异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个服务API调用.被调用方在性能上非常关键,因此为了不使API调用的中断时间不必要地更长,使用了 SaveAsync()方法.但是,我无法等待,因为那样会使API调用的时间长于非异步版本的时间(甚至更长).

Lets say you have a service API call. The callee is somewhat performance critical, so in order not to hold up the API call any longer than necessary, there's an SaveAsync() method that is used. I can't await it, however, because that would hold up the API call just as long (or perhaps even longer) than the non-async version.

我要问的原因是:如果您不等待呼叫,则有可能返回 Task 对象收集垃圾了吗?如果是这样,那会中断正在运行的任务吗?

The reason I'm asking is this: If you don't await the call, is there a chance the Task object returned gets garbage collected? And if so, would that interrupt the running task?

推荐答案

我问的原因是:如果您不等待呼叫,返回的Task对象是否有可能被垃圾回收?

The reason I'm asking is this: If you don't await the call, is there a chance the Task object returned gets garbage collected?

通常,不,那不应该发生.将任务排队的底层 TaskScheduler ,通常会在期望的生命周期内保留对它的引用,直到完成为止.您可以在 TaskScheduler.QueueTask 的文档中看到:

Generally, no, that shouldn't happen. The underlying TaskScheduler which queues the task, usually keeps a reference to it for the desired life-time until it completes. You can see that in the documentation of TaskScheduler.QueueTask:

典型的实现方式是将任务存储在内部数据结构中,并由将来在某些时候执行这些任务的线程提供服务.

A typical implementation would store the task in an internal data structure, which would be serviced by threads that would execute those tasks at some time in the future.

您真正的问题将是ASP.NET SynchronizationContext,它可以跟踪运行时正在进行的所有异步操作.如果您的控制器操作在异步操作之前完成,那么您将获得异常.

Your real problem is going to be with the ASP.NET SynchronizationContext, which keeps track of any on-going asynchronous operation at runtime. If your controller action finishes prior to the async operation, you're going to get an exception.

如果要在ASP.NET中进行抛弃"操作,则应确保通过

If you want to have "fire and forget" operations in ASP.NET, you should make sure to register them with the ASP.NET runtime, either via HostingEnvironment.QueueBackgroundWorkItem or BackgroundTaskManager

这篇关于您是否需要等待异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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