4

I use a System.Threading.Timer object, and I set its period:

// period of 1 second
var timer = new Timer(CallBack, null, 0, 1000);

...

Now I want to get the period of my timer, how can I do?

Nick
  • 10,309
  • 21
  • 97
  • 201
  • If you explain why you want to do this perhaps the community can suggest alternative solutions instead – Patrick Nov 04 '12 at 20:21

4 Answers4

4

There is no supported way to do that. You have two options:

1) It's best to use System.Timers.Timer class, as it's more flexible, and safer to use in case of multi threaded use. If you want to know more about timers, and comparison between System.Windows.Forms.Timer, System.Timers.Timer and System.Threading.Timer, please read MSDN article about this subject.

2) Use reflection to access private member holding the period value. There are plenty of nice articles on how to do this, and you can use ILSpy to see which field you need to read. (it's timer.m_timer.m_timer.m_period in .NET 4.0, it may be the same in other versions too)

Nikola Radosavljević
  • 6,871
  • 32
  • 44
  • System.Timers.Timer is not thread safe. – Latency Oct 15 '21 at 02:57
  • There is unclarity in the documentation. MSDN Magazine article states `Instances of this timer class can be safely accessed from multiple threads.`. API document says `Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.`. I lean to trusting the magazine article, because it was written with focus on comparing `Timer` classes. API doc looks like it has generic warning against accessing instance methods from multiple threads. – Nikola Radosavljević Oct 15 '21 at 09:21
2

You don't. That is to say System.Threading.Timer does not support getting the period (or any other members as far as I know). The only way to approximately determine the period would be to time it yourself.

CrazyCasta
  • 26,917
  • 4
  • 45
  • 72
1

According to MSDN there is no way to achieve what you ask for.

Yahia
  • 69,653
  • 9
  • 115
  • 144
1

You can't using System.Threading.Timer but you can if you use System.Timers.Timer or System.Windows.Forms.Timer, there you have Timer.Interval property that you can check. You can further refer to this link to see the differences of this two implementations.

Community
  • 1
  • 1
Nikola Davidovic
  • 8,556
  • 1
  • 27
  • 33