0

I need some kind of a timer, but the problem with existing timers is: timer's callback is executed in some thread of threadpool. That's why callbacks need to be thread-safe and reentrant.

Idea like

while (true) 
{
    // do some work
    Thread.Sleep(1000); 
}

seems wrong to me. So what is idiomatic for periodic running action in single thread?

Alexandr
  • 105
  • 7
  • *"seems wrong to me"* - why? Creating a thread which sleep most of time is ok. – Sinatr Aug 12 '16 at 11:37
  • 1
    What's the problem with timers? Why *not* run in a threadpool thread? – Panagiotis Kanavos Aug 12 '16 at 11:37
  • @PanagiotisKanavos Because my callback isn't thread-safe, it can't be ran on different threads – Alexandr Aug 12 '16 at 11:40
  • 2
    Just because the timer runs on a separate thread doesn't mean that your callback method must be thread safe. You could synchronize access to that method. Also, the timer (if used correctly) will not fire while the previous call isn't finished, so there's no problem here. – Thorsten Dittmar Aug 12 '16 at 11:42
  • 3
    Thread safety deals with *concurrent* access from multiple threads to *fields and structures*. Using the same thread for the timer won't make your callback thread safe if eg the UI thread tries to access the *same* fields. A single thread or a threadpool thread are exactly the same will behave the same. – Panagiotis Kanavos Aug 12 '16 at 11:42
  • In this regard, whether you use a single separate thread or a threadpool thread is exactly the same - only one thread will call the callback at a time. If some other thread needs to read the modified data though, you'd probably have to make your callback threadsafe in both cases. What does your callback do? – Panagiotis Kanavos Aug 12 '16 at 11:45
  • @PanagiotisKanavos let me clear the things up a little: i need timer for periodic data generation. There is some `Generator`, which have internal state. What I am worring about: if different threads will call `generator.Generate()` I think some changes of its internal state could be not visible. One more detail: there will be only **one** callback executing at the moment, but it can be executed in different threads every time. I don't want synchronization, because it isn't free, and `Generate()` function is very light. – Alexandr Aug 12 '16 at 11:49
  • @Alexandr, http://stackoverflow.com/a/38522252/5794617. Instead of infinite loop, I use CancellationToken to control the thead state and ManualResetEvent to wait thread stopping – Artavazd Balayan Aug 12 '16 at 12:16

0 Answers0