C# 是否存储对来自 TPL 的任务的引用 [英] Does C# stores references to tasks from TPL

查看:22
本文介绍了C# 是否存储对来自 TPL 的任务的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我运行这样的代码

Task.Factory.StartNew(...).ContinueWith(...);

我不存储两个已创建任务的引用,所以我可以确定它们不会在开始之前或执行过程中被处理吗?如果是,那么这些任务的参考在哪里?

I don't store reference for neither of two created tasks so can I be sure that they won't be disposed before starting or at the process of executing? If yes then where do reference to these tasks are being held?

推荐答案

在两种情况下,系统持有对 TPL Task 的引用:

A reference to a TPL Task is held by the system under two conditions:

  1. 任务已安排
  2. 任务正在运行

Task 和任何子任务完成后,引用将被丢弃.代码中的引用将按预期运行.

Upon completion of the Task and any child tasks, the reference is thrown away. References in your code will behave as expected.

我相信您对垃圾收集和 Dispose 有一些困惑.这个问题可能对你有所启发.

I believe you have some confusion regarding garbage collection and Dispose. This question may enlighten you.

析构函数、处置和终结方法之间的区别

析构函数隐式调用了 Finalize 方法,它们在技术上是相同的.Dispose 可用于那些对象实现 IDisposable 接口...

Destructor implicitly calls the Finalize method, they are technically same. Dispose is available with those object which implements IDisposable interface...

您应该处理 Tasks 吗?

斯蒂芬·图布说:

没有.不要费心处理你的任务.

No. Don’t bother disposing of your tasks.

https://devblogs.microsoft.com/pfxteam/do-i-need-to-dispose-of-tasks/

这篇关于C# 是否存储对来自 TPL 的任务的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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