Last active
December 6, 2017 15:14
-
-
Save Alan-FGR/a45321d3bfa1598151b2e7749ce4cb23 to your computer and use it in GitHub Desktop.
Proving to some noobs that C# finalizers/dtors aren't reliable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Threading; | |
class Test | |
{ | |
public static long count = 0; | |
public static int dtorTime = 201; | |
readonly long[] bogus_ = new long[1ul<<12]; | |
private long c; | |
public Test() | |
{ | |
c = Interlocked.Increment(ref count); | |
} | |
~Test() | |
{ | |
Thread.Sleep(dtorTime); | |
Interlocked.Decrement(ref count); | |
Console.WriteLine($"{c} DESTROYED!!!"); | |
} | |
} | |
class TestH | |
{ | |
public void TestM() | |
{ | |
List<Test> list = new List<Test>(); | |
for (int i = 0; i < 4; i++) | |
list.Add(new Test()); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
if (new Random().Next(2) == 0) | |
{ | |
Console.WriteLine("application will quit before dtors finish"); | |
Test.dtorTime = 2010; | |
} | |
for (int i = 0; i < 4; i++) | |
{ | |
new TestH().TestM(); | |
} | |
Console.WriteLine($"balance: {Test.count}"); | |
// GC.Collect(); | |
// GC.WaitForPendingFinalizers(); | |
Console.WriteLine($"final balance: {Test.count}"); | |
//Console.ReadKey(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The Noob has to make it MT safe