17 Sep 2010

System.Windows.Forms.Timer is not Working in Windows Service

I’m really surprised to know that System.Windows.Forms.Timer is not working in Windows Service project type. The reason from Microsoft is just like this,

“Server-based timers use the thread pool internally, and the event handler runs in a thread taken from the pool. For this reason, conflicts might occur while the event handler is accessing shared variables and modifying controls and forms.”

For this reason, you can’t use the System.Windows.Forms.Timer to periodically run your custom code. Replace it to System.Timers.Timer will help you resolve the situation. I’m using Visual Studio 2010, so it’s very simple to change this code. After adding the ProjectInstaller to the project, then you see your Windows Service Class, and open it, so VS will open the designer for you.

Your windows service class 

After open, just add the System.Windows.Forms.Timer from the Toolbox window.

image

Right after that, open the (+) sign before your Windows Service class file in the Solution Explorer window, and open the “Designer.cs” (depending your project, it can be “Designer.vb”). In my project, the file is “ServerCommand.Designer.cs”, double click that file.

image

Change the content of “InitializeComponents” method, change the System.Windows.Forms.Timer to System.Timers.Timer. See the surrounding red background.

image

And, you’re done. You can add the Timer elapsed event. Double click your Windows Service class file. Double click your timer, and the “Elapsed” event should be added to the code.

image

And this is the example code for Elapsed event,

private void Tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
EvLog.WriteEntry("Ex Message", EventLogEntryType.Information);
try
{
System.IO.File.AppendAllText(@"D:\PIS-ServiceCommand " + DateTime.Now.ToString("dd-MMM-yyyy HH-mm-sss", System.Globalization.CultureInfo.CreateSpecificCulture("id-ID")) + ".txt", "sss");
} catch (Exception ex)
{
EvLog.WriteEntry(ex.Message, EventLogEntryType.Error);
}
}


Happy Coding…

Tidak ada komentar:

Posting Komentar

[give me your ideas, hopes, comments and compliments below...]
[aaand...... +1 if you need to....]