gpt4 book ai didi

.net - 为什么垃圾收集器不收集任务对象

转载 作者:行者123 更新时间:2023-12-02 09:25:00 25 4
gpt4 key购买 nike

尤其是当没有事件线程引用它时。

我认为 GC 会考虑所有 .net 线程来查找引用...它是否也检查其他地方的引用?

编辑:例如,假设我们在控制台应用程序中,main 调用创建本地 task1 的方法,然后应用 task1.ContinueWith(task2) 并返回到 main,main 执行 console.readline()。

此时可能是 task1 已完成,task2 仍未启动 GC 可以启动并且没有线程引用 task2。为什么 task2 没有被 GC 处理?

EDIT2:可能我在说“任务”时没有使用正确的词

using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication
{
class Program
{
static void Launch()
{
var task1 = Task.Run(() => Thread.Sleep(60000))
task1.ContinueWith(() => WriteToFile("Hi"));
}

static void Main(string[] args)
{
Launch();
//At this point if a GC occurs which thread or static file has a reference to "()=>WriteTofile("Hi")" ?
Console.ReadLine();
}

有一个等待控制台的主线程,一个运行 sleep 的线程(可能来自线程池)。就在 Sleep 完成之后,WriteToFile 线程开始之前,可能会发生 GC,不是吗?

最佳答案

正在保留对task1 的引用by the default task scheduler ,(默认任务调度程序 is static)。

is kept alive by task1直到它被移交给它分配的任务调度程序(TaskScheduler.Current 在创建时默认情况下)。

(请注意,这些可能不是唯一可能的根源,只是我通过源代码快速找到的根源)

关于.net - 为什么垃圾收集器不收集任务对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38531077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com