123
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SystemGC { class Program { static void Main(string[] args) { SomeClass sc = new SomeClass(); // some code GC.Collect(0, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); // some code Console.WriteLine( GC.GetGeneration(sc) + "\n\r" + GC.CollectionCount(0) + "\n\r" + GC.CollectionCount(0) + "\n\r" + GC.CollectionCount(0) ); } public class SomeClass { } } } |
Finalizer for unmanaged resources My Resource Wrapper
1 2 3 4 5 6 7 8 |
class MyResourceWrapper { ~MyResourceWrapper() { //free resources here Console.Beep(); } } |
IDisposable
1 2 3 4 5 6 7 8 9 10 11 |
class MyResourceWrapper2:IDisposable // << implement IDisposable here { public void Dispose() { // free resources here Console.Beep(); } } |
using Dispose in Main
1 2 3 |
MyResourceWrapper2 rw2 = new MyResourceWrapper2(); // do something if (rw2 is IDisposable) rw2.Dispose(); |
try finally Dispose
1 2 3 |
if (rw2 is IDisposable) rw2.Dispose(); try {/*do smth*/ } finally { if (rw2 is IDisposable) rw2.Dispose(); } |
using = try/finally
1 2 |
using (MyResourceWrapper2 rw2 = new MyResourceWrapper2()) { } |
combination of Finalization and Dispose()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class MyResourceWrapper3 : IDisposable { ~MyResourceWrapper3() { //free all unmanaged resources } public void Dispose() { //free all unmanaged resources //if called Dispose supress Finalization GC.SuppressFinalize(this); } } |
template from microsoft
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class MyResourceWrapper4 : IDisposable { private bool disposed=false; public void Dispose() { CleanUp(true); GC.SuppressFinalize(this); } public void CleanUp(bool disposing) { if (!this.disposed) { if (disposing) {/*dispose all unmanaged resources*/ } } disposed = true; } ~MyResourceWrapper4() { /*dispose all unmanaged resources*/ CleanUp(false); } } |