2

I'm trying to build a library that internally executes task in an exclusive TaskScheduler built as following:

schedulerPair = new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, 1);
simulationFactoryTask = new TaskFactory(schedulerPair.ExclusiveScheduler);

I use the System.Threading.Timer class:

timer = new Timer(Tick, this, startTime, deltaTime);

That periodically calls my Tick method:

static void Tick(object? state)
{
    var self = state as MyTimerScheduler;

    // fake computation
    Thread.Sleep(10_000);
}

The issue is that the Tick method is executed inside a different thread and not in the one inside my schedulerPair.

One solution is to schedule a new Task like that:

static void Tick(object? state)
{
    var self = state as MyTimerScheduler;

    // This shouldn't be needed
    self.simulationFactoryTask.StartNew(() =>
    {
        // fake computation
        Thread.Sleep(10_000);
    });
}

Is it possible to schedule Tick inside schedulerPair TaskScheduler?

EduBic
  • 227
  • 4
  • 17
  • 1
    Aren't you worried that the duration of the work might be longer than the interval between ticks, causing an ever increasing number of tasks scheduled through your `schedulerPair.ExclusiveScheduler`? – Theodor Zoulias Aug 17 '23 at 10:37
  • Yes, since the computational work is a simulation step, often the majority of task execution time is less than deltaTime (hyperparameter to be defined). But sure it's something to be aware of. – EduBic Aug 17 '23 at 11:28
  • 1
    You can find some ideas about solving this problem here: [Run async method regularly with specified interval](https://stackoverflow.com/questions/30462079/run-async-method-regularly-with-specified-interval). – Theodor Zoulias Aug 17 '23 at 11:32

1 Answers1

3

No, as per docs:

The timer delegate is specified when the timer is constructed, and cannot be changed. The method does not execute on the thread that created the timer; it executes on a ThreadPool thread supplied by the system.

And

System.Threading.Timer is a simple, lightweight timer that uses callback methods and is served by thread pool threads.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132