0

I know how to call method after interval.

public void afterInt(int s) {
    Task.Factory.StartNew(() => {
        System.Threading.Thread.Sleep(s);
        // calling method
    });
}

But I don't wanna create a new task for each scroll event, I'd like to:

  1. edit a interval for a current task

or

  1. remove a current task and create a new one with a new interval

May anybody help me with that? I have no clue where to start.

John Doe
  • 21
  • 1
  • You could probably do that pretty easily with timers. Sleep is generally frowned upon for timing/interval work anyway. – Broots Waymb Apr 13 '20 at 17:13
  • All you need is [`Task.Delay()`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.delay). You can/should get rid of this method altogether and simply use something like `await Task.Delay(ms);` where `ms` is the amount you want to wait in milliseconds. – 41686d6564 stands w. Palestine Apr 13 '20 at 17:16
  • Check the answers in this question: [When to use Task.Delay, when to use Thread.Sleep?](https://stackoverflow.com/questions/20082221/when-to-use-task-delay-when-to-use-thread-sleep) – 41686d6564 stands w. Palestine Apr 13 '20 at 17:19
  • Thanks a lot! That's weird. I have `public static System.Timers.Timer timer = new System.Timers.Timer();` in `public partical class Form1` and `timer.Elapsed` gets me this: `timer.Elapsed does not exist in current context`. What do I do wrong? – John Doe Apr 13 '20 at 17:22
  • Have you started the timer? timer.Start() – Patrick Mcvay Apr 13 '20 at 17:32
  • Thansk a lot' That was the problem! What is better to use: Task.Delay or Timer? – John Doe Apr 13 '20 at 17:33
  • Technically Task.Delay uses a Timer. So I don't think it really matters. In my opinion, if you are expecting something to happen at a set interval (like once every 5 seconds) then I would say use a timer. If you just need a one shot timer (like I want this to happen only once 5 seconds after this happens) then I would say use Task.Delay. – Patrick Mcvay Apr 13 '20 at 18:15

0 Answers0