您需要等待计时器做什么?
.NET 中“我可以等待的东西”的默认类是System.Threading.Tasks.Task http://msdn.microsoft.com/en-us/library/vstudio/system.threading.tasks.task(v=vs.100).aspx。在.NET 4.5中,您可以简单地使用Task.Delay(milliseconds) http://msdn.microsoft.com/en-us/library/vstudio/hh194873(v=vs.110).aspx.
在 .NET 4.0 中,您可以使用TaskCompletionSource http://msdn.microsoft.com/en-us/library/dd449174(v=vs.110).aspx创建任务,并使用普通计时器将其设置为已完成。或者使用TaskEx.Delay
实施从异步定位包 http://www.microsoft.com/en-us/download/details.aspx?id=29576 or 异步桥 http://omermor.github.io/AsyncBridge/
如果您需要实际的WaitHandle http://msdn.microsoft.com/en-us/library/system.threading.waithandle(v=vs.110).aspx,你可以使用ManualResetEvent http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent(v=vs.110).aspx,并使用普通的 .NET 计时器来设置事件。
或者,您可以创建自己的类,派生自WaitHandle
和 P/调用CreateWaitableTimer http://msdn.microsoft.com/en-gb/library/windows/desktop/ms682492(v=vs.85).aspx。
看起来.NET框架中已经存在这样的类,但它是内部的。 (System.Runtime.IOThreadTimer.WaitableTimer http://referencesource.microsoft.com/#System.ServiceModel.Internals/System/Runtime/IOThreadTimer.cs#601 from 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();
}
}
}