Skip to content

Instantly share code, notes, and snippets.

@Alan-FGR
Last active December 6, 2017 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alan-FGR/a45321d3bfa1598151b2e7749ce4cb23 to your computer and use it in GitHub Desktop.
Save Alan-FGR/a45321d3bfa1598151b2e7749ce4cb23 to your computer and use it in GitHub Desktop.
Proving to some noobs that C# finalizers/dtors aren't reliable :trollface:
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();
}
}
@nem0
Copy link

nem0 commented Dec 6, 2017

The Noob has to make it MT safe :trollface:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment