Here’s some interesting code I thought I might share. It’s an asynchronous timer, and allows you, in Windows Forms, to have a simple timer where you specify an interval, a condition, some code to execute on the interval, and optionally some other code to execute after the timer condition evaluates to false. One thing to be careful of though, is I am not following best practices here: This is an async void method, which polls.
Again, the source, for this and a whole bunch of other stuff, is here: RomyView.zip
- /// <summary>Starts an asynchronous polling timer, similar to a thread timer.</summary>
- /// <param name=”condition”>The condition which indicates that polling should continue.</param>
- /// <param name=”pollInterval”>Similar to a timer tick, this determines the polling frequency.</param>
- /// <param name=”pollingAction”>The action to be executed after each poll interval, as long as the condition
- /// evaluates to true. This works like a timer event handler.</param>
- /// <param name=”afterAction”>An optional action to be executed after the condition evaluates to false.</param>
- protected async void CreatePollingTimerAsync(Func<bool> condition, TimeSpan pollInterval, Action pollingAction, Action afterAction = null)
- while (condition())
- await Task.Delay(pollInterval);
- if (condition())
- if (afterAction != null)
And some examples of using it…
This is the simplest one. Called from my video player, it ensures that while the form is visible, the system will not enter Sleep mode. (PowerManagement.DisplayIsInUse() just calls the WindowsAPI SetThreadExecutionState method. I’ll include that here as well, for clarity.)
- protected void IndicateDisplayInUse()
- CreatePollingTimerAsync(() => !IsDisposed && Visible, TimeSpan.FromMinutes(1), () => PowerManagement.DisplayIsInUse());
Here is the PowerManagement code:
- using System.Runtime.InteropServices;
- namespace System
- /// <summary>Notifies the system that the display is in use. To be used, for example,
- /// when playing video, since the system is unable to detect video activity alone and
- /// will incorrectly detect that it is idle, and enter sleep mode.</summary>
- public static class PowerManagement
- /// <summary>Informs the system that the display is in use.</summary>
- public static void DisplayIsInUse()
- internal static class NativeMethods
- [DllImport(“kernel32.dll”, SetLastError = true)]
- public static extern ExecutionStates SetThreadExecutionState(ExecutionStates esFlags);
- internal enum ExecutionStates
- /// <summary>No state configured.</summary>
- None = 0,
- /// <summary>Forces the system to be in the working state by resetting the system idle timer.</summary>
- SystemRequired = 0x1,
- /// <summary>Forces the display to be on by resetting the display idle timer.</summary>
- DisplayRequired = 0x2,
- /// <summary>Enables away mode. This value must be specified with ExecutionStates.Continuous.
- /// Windows Server 2003 and Windows XP/2000: ExecutionStates.AwayModeRequired is not supported.</summary>
- AwayModeRequired = 0x40,
- /// <summary>Informs the system that the state being set should remain in effect until the next
- /// call that uses ExecutionStates.Continuous and one of the other state flags is cleared.</summary>
- Continuous = unchecked((int)0x80000000)
And here is another example of using the timer. I won’t copy all the related code here though… It is used in my video player, and all it does is, as long as the video is still playing (and hence we are seeking), it updates the seeking slider.
One must be careful with the first parameter to this method. Below, the first parameter being passed is a lambda expression that will cause my video player’s Seeking property to be evaluated each time. Passing a boolean value here, instead of a lambda expression or delegate, would be a mistake, because that would cause the condition to always evaluate to whatever that boolean value passed initially is, which is of course not the intention.
- /// <summary>An async timer to update the slider.</summary>
- private void Seek()
- CreatePollingTimerAsync(() => Seeking, TimeSpan.FromMilliseconds(100), () => UpdateSeeker());
Update: What is the significance of this being an async void method that polls?
It depends… Mine is being called from a Form. In that case, depending on the length of the interval duration, the timer might just tick after the Form is already disposed. So the code needs to handle that. It’s not a big deal in my video player, because the form is hidden and not closed after playing video. But notice in my first example, I added a check for the form being disposed before checking its Visible property, to avoid a potential exception if the timer ticks while the application is being closed.