c# my destructor isn't being called?

前端 未结 3 1338
说谎
说谎 2021-01-14 11:54

I have this simple code and trying to call the destructor but I can\'t call it :(

I know that GarbageCollector runs when it\'s necessary, so I used GC.WaitForPending

3条回答
  •  感情败类
    2021-01-14 12:22

    I would not recommend to really on destructors .net

    anyway in your case GC don't think your object is garbage at the moment you calling GS because you have alive link in your stack calculator which is point to object in heap so you can try to modify this code

    main(){
      DoCalculations();
      //at this point object calculator is garbage (because it was allocated in stack)
      GC.Collect();
    }
    DoCalculations(){
      Calculator calculator = new Calculator(); // object allocated
      calcualtor.doSomething();  //link alive
    }
    

提交回复
热议问题