C# about Windows service
What would be a short example with a Windows service and how to install and run it?
I've searched on the Internet, but what I've tried didn't have anything written on the On Start method. Plus, when I've tried to install it the error 开发者_运维技巧OpenSCManager
keeps popping up.
Find install util at
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe
Then run
InstallUtil.exe "c:\myservice.exe"
Go to
services.msc
and then locate and start your service
Here are some examples about how to write and install a Windows service in C#:
- A Windows Service Application
- Simple Windows Service Sample
- ASP.NET Tutorials : Creating Windows Service in C#
- Creating a Windows Service in C#
- How to Create and Work With Windows Services in C#
- Creating a Simple Windows Service in C#
My answer to this question gives you step-by-step instructions for creating a Windows service in C#.
- Easiest language for creating a Windows service
My answer to this question shows you have to modify the service so that it can install and uninstall itself from the command line.
- How to make a .NET Windows Service start right after the installation?
InstallUtil.exe has been part of .NET since 1.1, so it should be on your system. However, you likely can't use it from a 'normal' command prompt. If you have Visual Studio installed, open the Visual Studio command prompt. That'll define the appropriate environment variables that make InstallUtil accessible without path information.
The OnStart()
callback gives you an opportunity to start the business logic of your service. If you don't do anything in the OnStart()
callback, your service will immediately shut down. Typically, you'll start a thread that performs the work you're interested in. Here is a small example to show you what it looks like.
private static System.Timers.Timer _timer;
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// Write a message to the event log.
string msg = String.Format("The Elapsed event was raised at {0}", e.SignalTime);
EventLog.WriteEntry(msg, EventLogEntryType.Information);
}
protected override void OnStart(string[] args)
{
// Create a timer with a 10-econd interval.
_timer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Signal the timer to raise Elapsed events every 10 seconds.
_timer.Start();
}
protected override void OnStop()
{
// Stop and dispose of the timer.
_timer.Stop();
_timer.Dispose();
}
Doing something like this will effectively keep your service running until it shuts down. Hope this helps.
精彩评论