Export (0) Print
Expand All

ServiceBase.OnStart Method

When implemented in a derived class, executes when a Start command is sent to the service by the Service Control Manager (SCM) or when the operating system starts (for a service that starts automatically). Specifies actions to take when the service starts.

Namespace:  System.ServiceProcess
Assembly:  System.ServiceProcess (in System.ServiceProcess.dll)

protected virtual void OnStart(
	string[] args
)

Parameters

args
Type: System.String[]
Data passed by the start command.

Use OnStart to specify the processing that occurs when the service receives a Start command. OnStart is the method in which you specify the behavior of the service. OnStart can take arguments as a way to pass data, but this usage is rare.

Caution noteCaution

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.

Services can be set to start automatically when the computer reboots by setting the StartType on the service's installer to Automatic. In such a situation, OnStart would be called at system startup.

OnStart is expected to be overridden in the derived class. For the service to be useful, OnStart and OnStop should both be implemented in your service class.

Process initialization arguments for the service in the OnStart method, not in the Main method. The arguments in the args parameter array can be set manually in the properties window for the service in the Services console. The arguments entered in the console are not saved; they are passed to the service on a one-time basis when the service is started from the control panel. Arguments that must be present when the service is automatically started can be placed in the ImagePath string value for the service's registry key (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<service name>). You can obtain the arguments from the registry using the GetCommandLineArgs method, for example: string[] imagePathArgs = Environment.GetCommandLineArgs();.

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Community Additions

ADD
Show:
© 2014 Microsoft