0

There is a timer, its callback must be executed once:

var timer = new Threading.Timer(callback: MyCallback, state: NotNullObject, dueTime: Timeout.Infinite, period: Timeout.Infinite);
//note state is some not-null object
//timer is local variable 

//there is some code...
timer.Change(new TimeSpan(0, 0, 5), Timeout.InfiniteTimeSpan); //launch timer in 5 seconds

According this answer, if state argument is not null then garbage collector does not collect the timer. So why MyCallback never be executed here?

And there is another related question: if state argument is not null and timer is needed for once-only operation does it mean GC can not collect this timer later? i.e. is needless memory consumption in this case?

Community
  • 1
  • 1
Ilya Loskutov
  • 1,967
  • 2
  • 20
  • 34
  • 1
    Is there a reference to your state object anywhere? – eitamal Dec 25 '16 at 14:10
  • @eitamal I store this object (or rather reference to it) as key in ConcurrentDictionary (dict is global var) – Ilya Loskutov Dec 25 '16 at 14:16
  • How is NotNullObject defined? – TaW Dec 25 '16 at 16:22
  • @TaW it's string, I create a local variable which references to string property of some class sample. Next I send it to timer (as state arg) and save in a global Concurrent Dictionary as key (so I think dict must store the same object which is in the timer) – Ilya Loskutov Dec 25 '16 at 16:49
  • Hm, not sure here. Strings get copied by value, despite being objects. Can you try using a 'real' reference object to test if that is the problem.. – TaW Dec 25 '16 at 16:57

0 Answers0