Skip to content

Commit

Permalink
Enable TimeSpan with WaitableTimer.
Browse files Browse the repository at this point in the history
  • Loading branch information
tosh-coding committed Jun 27, 2024
1 parent 5705dbe commit bc9a491
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/AsyncFiberWorks.Windows/Timer/WaitableTimerEx.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public WaitableTimerEx(bool manualReset = true, string timerName = null)
/// Activate the timer.
/// see https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-setwaitabletimerex
/// </summary>
/// <param name="dueTime">Initial wait time for timer. 100 nanosecond units.</param>
/// <param name="dueTime">Initial wait time for timer. 100 nanosecond units. Be sure to specify a negative value.</param>
/// <param name="period">The interval at which the timer expires. In milliseconds. If this value is 0, the timer will expire only once; if it is greater than 0, it will expire periodically and continue until canceled.</param>
/// <exception cref="Win32Exception"></exception>
public void Set(long dueTime, int period = 0)
Expand All @@ -60,6 +60,18 @@ public void Set(long dueTime, int period = 0)
}
}

/// <summary>
/// Activate the timer.
/// </summary>
/// <param name="dueTime">Initial wait time for timer.</param>
/// <param name="period">The interval at which the timer expires. In milliseconds. If this value is 0, the timer will expire only once; if it is greater than 0, it will expire periodically and continue until canceled.</param>
/// <exception cref="Win32Exception"></exception>
public void Set(TimeSpan dueTime, int period = 0)
{
long convertedDueTime = dueTime.Ticks * -10000L / TimeSpan.TicksPerMillisecond;
this.Set(convertedDueTime, period);
}

/// <summary>
/// Deactivate the timer.
/// see https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-cancelwaitabletimer
Expand Down
20 changes: 20 additions & 0 deletions src/AsyncFiberWorksTests/TimerActionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,5 +84,25 @@ public async Task OneshotTimerDelayTest(IOneshotTimerFactory timerFactory)
new object[] { new WaitableTimerExFactory() },
#endif
};

#if NETFRAMEWORK || WINDOWS
[Test]
public async Task CancelWaitableTimer()
{
var tcs = new TaskCompletionSource<int>();
var timer = new WaitableTimerEx();
timer.Set(TimeSpan.FromMilliseconds(300));
var tmpHandle = ThreadPool.RegisterWaitForSingleObject(timer, (state, timeout) =>
{
tcs.SetResult(0);
}, null, Timeout.Infinite, executeOnlyOnce: true);
await Task.Delay(100).ConfigureAwait(false);
bool isCancelled = timer.Cancel();
Assert.IsTrue(isCancelled);
await Task.Delay(500).ConfigureAwait(false);
Assert.IsFalse(tcs.Task.IsCompleted);
tmpHandle.Unregister(null);
}
#endif
}
}

0 comments on commit bc9a491

Please sign in to comment.