An analogue of expected timers in .NET.

In an unmanaged Win32 world, I use the expected timers created using the CreateWaitableTimer API , which can be used for synchronization calls such as WaitForSingleObject and mainly for WaitForMultipleObjects .

Should .NET and C # have an analog expected timer?

+5
source share
1 answer

What is the right timer for?

The default class for "something that I can wait" in .NET: System.Threading.Tasks.Task. In .NET 4.5 you can just use Task.Delay(milliseconds).

.NET 4.0 TaskCompletionSource . TaskEx.Delay Async Targeting Pack AsyncBridge

WaitHandle, ManualResetEvent .NET .

, WaitHandle P/Invoke CreateWaitableTimer. , .NET framework, . (System.Runtime.IOThreadTimer.WaitableTimer System.ServiceModel.Internals.dll)

public class WaitableTimer : WaitHandle
{
    [DllImport("kernel32.dll")]
    static extern SafeWaitHandle CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName);

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetWaitableTimer(SafeWaitHandle hTimer, [In] ref long pDueTime, int lPeriod, IntPtr pfnCompletionRoutine, IntPtr lpArgToCompletionRoutine, [MarshalAs(UnmanagedType.Bool)] bool fResume);

    public WaitableTimer(bool manualReset = true, string timerName = null)
    {
        this.SafeWaitHandle = CreateWaitableTimer(IntPtr.Zero, manualReset, timerName);
    }

    public void Set(long dueTime)
    {
        if (!SetWaitableTimer(this.SafeWaitHandle, ref dueTime, 0, IntPtr.Zero, IntPtr.Zero, false))
        {
            throw new Win32Exception();
        }
    }
}
+6

All Articles