Skip to content

Instantly share code, notes, and snippets.

@dabbinavo
Last active March 17, 2023 09:35
Show Gist options
  • Save dabbinavo/8df43436909f6b217b7e4a9c9eba2a83 to your computer and use it in GitHub Desktop.
Save dabbinavo/8df43436909f6b217b7e4a9c9eba2a83 to your computer and use it in GitHub Desktop.
How does c# Lifetime work?
using System.Diagnostics;
using System.Threading;
namespace LifeTimeTest;
public class LifeTimeTest
{
public LifeTimeTest()
{
//TestLifeTime(42); // Outputs 43 one time
//TestLifeTime2(42); // Outputs every second: 43, 44, 45, 46, ...
//TestLifeTime3(42); // Outputs 43 every second
TestLifeTime4(42); // Outputs every second: 43, 44, 45, 46, ... Safe to use????
}
Timer? field1;
Timer? field2;
void TestLifeTime(int i)
{
var local1 = new Timer(_ => i += 1, null, 0, 1000);
var local2 = new Timer(_ => Debug.WriteLine(i), null, 0, 1000);
}
void TestLifeTime2(int i)
{
field1 = new Timer(_ => i += 1, null, 0, 1000);
field2 = new Timer(_ => Debug.WriteLine(i), null, 0, 1000);
}
void TestLifeTime3(int i)
{
var local1 = new Timer(_ => i += 1, null, 0, 1000);
field2 = new Timer(_ => Debug.WriteLine(i), null, 0, 1000);
}
void TestLifeTime4(int i)
{
var local1 = new Timer(_ => i += 1, null, 0, 1000);
field2 = new Timer(_ => Debug.WriteLine($"{local1} {i}"), null, 0, 1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment