Ankh Morpork's Finest Coder
Sunday, October 17, 2004
Tick Tock Tick Tock
I didn't realize that .Net had 3 types of timers. I have always used the System.Windows.Forms.Timer when I needed to do any timer related processing. Apparently, there is one provided by the System.Threading class that is pretty reliable (more reliable than the one provided by Forms).
I feel quite stupid not having known this but it just goes to show that .Net is just such a vast framework.
So how do u code using the Threading Timer you ask. Well, I'll show you a neat little piece to play a wave file while processing some data in the background. That way users know that the application is functioning.
1) Add the Using clause.
2) Add the DllImport statement.
[DllImport("winmm.dll", SetLastError=true, CallingConvention=CallingConvention.Winapi)]
static extern bool PlaySound( string pszSound, IntPtr hMod, SoundFlags sf );
3) Add the SoundFlags enumerator in order to pass the information to the PlaySound() method.
public enum SoundFlags : int
SND_SYNC = 0x0000, /* play synchronously (default) */
SND_ASYNC = 0x0001, /* play asynchronously */
SND_NODEFAULT = 0x0002, /* silence (!default) if sound not found */
SND_MEMORY = 0x0004, /* pszSound points to a memory file */
SND_LOOP = 0x0008, /* loop the sound until next sndPlaySound */
SND_NOSTOP = 0x0010, /* don't stop any currently playing sound */
SND_NOWAIT = 0x00002000, /* don't wait if the driver is busy */
SND_ALIAS = 0x00010000, /* name is a registry alias */
SND_ALIAS_ID = 0x00110000, /* alias is a predefined ID */
SND_FILENAME = 0x00020000, /* name is file name */
SND_RESOURCE = 0x00040004 /* name is resource name or atom */
4) Add a Using clause to the part of the code that you want your timer to run on.
using (System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(PlayWavFile), null, 0, 5000))
// DO SOME PROCESSING HERE
5) Add the PlayWavFile method.
private void PlayWavFile(Object state)
int err = 0; // last error
// play the sound from the selected filename
if (!PlaySound( @"C:\SoundFile.wav", IntPtr.Zero, SoundFlags.SND_FILENAME SoundFlags.SND_ASYNC ))
MessageBox.Show(this, "Unable to find specified sound file or default Windows sound");
err = Marshal.GetLastWin32Error();
if (err != 0)
MessageBox.Show( this, "Error " + err.ToString(), "PlaySound() failed", MessageBoxButtons.OK, MessageBoxIcon.Error );
I know the code looks manageled but thats only because Blogger in all its wisdom doesn't have code snippet technology. I've written to them and asked them about it and i'll fix this if they do.