您是否需要等待异步方法?

编程入门 行业动态 更新时间:2024-10-22 23:08:46
本文介绍了您是否需要等待异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设您有一个服务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中进行抛弃"操作,则应确保通过 HostingEnvironment.QueueBackgroundWorkItem 或 BackgroundTaskManager

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

更多推荐

您是否需要等待异步方法?

本文发布于:2023-11-05 07:54:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560289.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:您是否   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!