Search code examples
c#.net-coretimerasync-awaittask-parallel-library

RegisterWaitForSingleObject vs System.Timers


I need my code to execute after waiting for a specific time. This should happen asynchronous without blocking my thread. I searched the web and found many ways to do this. Two options are to use the System.Timers or to use RegisterWaitForSingleObject and a ManualResetEvent.

I couldn't really figure out the difference or when to prefer one over the other. Can you tell me briefly why and when to use Timers or RegisterWaitForSingleObject with ManualResetEvent?

Sidenote: I'm fond of TAP and TPL and generally prefer those over other patterns (but is this the only reason for not using System.Timer?)


Solution

  • Timers

    You use Timers when you want the same code to run multiple times, with a specific amount of time in between.

    RegisterWaitForSingleObject

    The documentation says it best:

    Registers a delegate that is waiting for a WaitHandle.

    And a WaitHandle is used when you want to

    wait for exclusive access to shared resources.

    If you're not waiting for shared resources, then it's not appropriate for your use case.

    ManualResetEvent

    The documentation says

    Represents a thread synchronization event that, when signaled, must be reset manually.

    The "signalling" and "resetting" are things that your code needs to do. It's used when one of your threads needs to signal to another of your threads that it can continue.

    Your use case

    You said:

    I need my code to execute after waiting for a specific time.

    If you do not need to repeat the code over and over, and you aren't waiting for shared resources, and you aren't waiting for another thread, then none of the above methods are appropriate.

    If you really just need to wait a specific amount of time before moving on, then, as mentioned already, use Task.Delay:

    await Task.Delay(5000); //wait 5 seconds