I l @ ve RuBoard |
Visual Studio .NET makes it extremely easy to create a Windows service. If you've mastered the primary mouse-button click, you're well on your way to creating your first service. The following example shows part of the code that Visual Studio .NET inserts when you create a new Visual Basic Windows Service project. Here are the steps for creating a bare-bones service:
The OnStart method is where you should place any initialization code and code that is necessary for starting and running the service. When the ServiceBase.Run method is called, the service is loaded into memory and the constructor is called. When the service is started, the Service Control Manager (SCM) sends a Start command to the service, which in turn invokes the OnStart method in the service. The OnStop method is where you should dispose of any resources your service allocated. Warning Do not place any initialization code in the class constructor that must be executed each time the service is started. The class constructor is called only once by the Service Control Manager ”the first time the service is loaded. Subsequent attempts to start the service will most likely fail because this initialization code will not be executed. Warning Do not perform a long-running or blocking command in the OnStart method. This method should simply start a timer or another thread and then return immediately; otherwise , the service will fail to start. ServiceBase also defines several properties and other methods that can be overridden. Tables 7-4 and 7-5 list the properties and the protected methods of the ServiceBase class, respectively. Table 7-4. ServiceBase Properties
Table 7-5. ServiceBase Overridable Methods
The OnCustomCommand method can be overridden in your derived ServiceBase class. This method takes one parameter ”an integer whose value must be between 0 and 256. Values below 128 correspond to system-reserved values. If the AutoLog property is set to true , custom commands will log an entry to the event log to report the failure or success of the method execution. One interesting characteristic of services is that they can share a process with other services. Visual Studio .NET is capable of creating two types of services. These correspond to the Win32OwnProcess and Win32ShareProcess ServiceType enumerations. In Visual Studio .NET you cannot create service types that relate to hardware, file system, or other device drivers. With the basics of creating a service covered, we will now move on to creating an actual service. |
I l @ ve RuBoard |