相关疑难解决方法(0)

处理,何时被称为?

请考虑以下代码:

namespace DisposeTest
{
    using System;

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Calling Test");

            Test();

            Console.WriteLine("Call to Test done");
        }

        static void Test()
        {
            DisposeImplementation di = new DisposeImplementation();
        }
    }

    internal class DisposeImplementation : IDisposable
    {
        ~DisposeImplementation()
        {
            Console.WriteLine("~ in DisposeImplementation instance called");
        }
        public void Dispose()
        {
            Console.WriteLine("Dispose in DisposeImplementation instance called");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

即使我在Test();调用之后放置了一个等待循环,Dispose也永远不会被调用.所以这很糟糕.我想编写一个简单易用的类,以确保清理所有可能的资源.我不想把这个责任交给我班级的用户.

可能的解决方案:使用using或调用自己处理(基本相同).我可以强制用户使用吗?或者我可以强制调用处理吗?

呼叫GC.Collect();Test();也不起作用.

dinull不调用任何处置.解构器可以工作,因此对象在退出时会被解构Test()

好的,现在很清楚!

谢谢大家的答案!我会在评论中添加警告!

.net c# garbage-collection dispose idisposable

29
推荐指数
4
解决办法
4万
查看次数

标签 统计

.net ×1

c# ×1

dispose ×1

garbage-collection ×1

idisposable ×1