1: using System;
2:
3: namespace Example
4: {
5: public class Test4
6: {
7: private static int intTest4Count = 0;
8: public string strMyValue;
9: public Test4(string inMyValue)
10: {
11: Console.WriteLine(" Test4 ({0}) Constructor",inMyValue);
12: if(MemoryExample.objHolder != null)
13: {
14: ((Test4)MemoryExample.objHolder).Dispose();
15: MemoryExample.objHolder = null;
16: }
17: strMyValue = inMyValue;
18: intTest4Count++;
19: }
20:
21: //protected override void Finalize()
22: //see the note above
23: ~Test4()
24: {
25: Console.WriteLine(" Test4 Finalize [{0}][{1}]", strMyValue,intTest4Count--);
26: if (intTest4Count <= 0)
27: {
28: Console.WriteLine(" Test4 Resurrecting [{0}][{1}]", strMyValue,++intTest4Count);
29: MemoryExample.objHolder = this;
30: GC.ReRegisterForFinalize(this);
31: }
32: else
33: {
34: MemoryExample.objHolder = null;
35: }
36: }
37:
38: public void Dispose()
39: {
40: Console.WriteLine(" Test4 Dispose [{0}][{1}]", strMyValue,intTest4Count--);
41: GC.SuppressFinalize(this);
42: }
43: }
44:
45: public class MemoryExample
46: {
47: static public object objHolder; // defaults to null
48:
49: static void Main(string[] args)
50: {
51: object one;
52: object two;
53:
54: Console.WriteLine("BEGIN:");
55: one = new Test4("blarg");
56: two = new Test4("futz");
57: one = null;
58: two = null;
59: Console.WriteLine(" Start First Collection Point");
60: GC.Collect();
61: GC.WaitForPendingFinalizers();
62: Console.WriteLine(" End First Collection Point");
63:
64: one = new Test4("blarg2");
65: two = new Test4("futz2");
66: ((Test4)one).Dispose();
67: one = null;
68: ((Test4)two).Dispose();
69: two = null;
70: Console.WriteLine(" Start Second Collection Point");
71: GC.Collect();
72: GC.WaitForPendingFinalizers();
73: Console.WriteLine(" End Second Collection Point");
74: Console.WriteLine("END");
75: }
76: }
77: }
78: