gpt4 book ai didi

c# - 在这种情况下什么时候调用我的析构函数? (C#)

转载 作者:太空狗 更新时间:2023-10-29 20:45:52 25 4
gpt4 key购买 nike

我想知道在这种情况下什么时候调用析构函数,如果是,它会在主 UI 线程上调用吗?

假设我有以下代码,什么时候调用析构函数,它会等到我完成所有函数调用后才调用吗?

private void Foo()
{
MyObject myObj = new MyObject();
DoSomeFunThingsWithMyObject(myObj);

myObj = new MyObject(); //is the destructor for the first instance called now?
DoLongOminousFunctionality(myObj);
}
//Or will it be called after the DoLongOminousFunctionality?

这只是我感兴趣的事情,如果线程在 myObj = new MyObject() 处被中断,或者如果 Destructor 调用一直等到线程空闲。

感谢您提供信息。

最佳答案

当垃圾收集器决定它必须清理一些旧对象时,将调用析构函数。您不能依赖 .NET 中的析构函数执行时间

如果你想在不需要时清理一些资源(尤其是当你有任何非托管资源,如 TCP 连接、SQL 连接等),你应该使用 Dispose() 代替它

参见 Implementing a Dispose Method

关于c# - 在这种情况下什么时候调用我的析构函数? (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1259628/

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