Versión imprimible       Enviar     
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Esta página es específica de
Microsoft Visual Studio 2005/.NET Framework 2.0

Hay además otras versiones disponibles para:
ServiceBase.OnStart (Método)
Si se implementa en una clase derivada, se ejecuta cuando el Administrador de control de servicios (SCM, Service Control Manager) envía un comando Iniciar al servicio o cuando se inicia el sistema operativo (en el caso de un servicio que se inicia de forma automática). Especifica las acciones que deben realizarse cuando se inicia el servicio.

Espacio de nombres: System.ServiceProcess
Ensamblado: System.ServiceProcess (en system.serviceprocess.dll)

Visual Basic (Declaración)
Protected Overridable Sub OnStart ( _
    args As String() _
)
Visual Basic (Uso)
Dim args As String()

Me.OnStart(args)
C#
protected virtual void OnStart (
    string[] args
)
C++
protected:
virtual void OnStart (
    array<String^>^ args
)
J#
protected void OnStart (
    String[] args
)
JScript
protected function OnStart (
    args : String[]
)
XAML
No aplicable.

Parámetros

args

Datos pasados por el comando Iniciar.

Hay que utilizar OnStart para especificar el proceso que tiene lugar cuando el servicio recibe un comando Iniciar. OnStart es el método en el que se especifica el comportamiento del servicio. OnStart puede aceptar argumentos como una forma de pasar datos, pero este uso no es corriente.

Nota de precauciónPrecaución:

No utilice el constructor para realizar procesamiento que tiene que estar en OnStart. Utilice OnStart para controlar toda la inicialización del servicio. Se llama al constructor cuando se ejecuta el ejecutable de la aplicación, no cuando se ejecuta el servicio. El ejecutable se ejecuta antes que OnStart. Cuando continúa, por ejemplo, no se llama al constructor de nuevo, porque el SCM conserva ya el objeto en la memoria. Si OnStop libera los recursos asignados en el constructor en lugar de en OnStart, los recursos necesarios no se crearán de nuevo la segunda vez que se llame al servicio.

Para que los servicios se inicien automáticamente al reiniciar el equipo, establezca el valor de la propiedad StartType del instalador del servicio en Automatic. En una situación como ésta, se llamará a OnStart cuando se inicie el sistema.

Se espera que OnStart se reemplace en la clase derivada. Para que el servicio sea útil, OnStart y OnStop tienen que implementarse en la clase de servicio.

Procese los argumentos de inicialización del servicio en el método OnStart, no en el método Main. Los argumentos de la matriz de parámetros args pueden establecerse manualmente en la ventana de propiedades del servicio en la consola Servicios. Los argumentos escritos en la consola no se guardan; se pasan al servicio de una sola vez cuando éste se inicia desde el panel de control. Los argumentos que deben estar presentes al iniciar el servicio automáticamente pueden colocarse en el valor de cadena ImagePath para la clave de Registro del servicio (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<nombre servicio>). Puede obtener los argumentos del Registro utilizando el método GetCommandLineArgs, por ejemplo: string[] imagePathArgs = Environment.GetCommandLineArgs();.

En el ejemplo siguiente se muestra una implementación del método OnStart para una clase de servicio derivada de ServiceBase. Este ejemplo de código forma parte de un ejemplo más amplio referente a la clase ServiceBase.

Visual Basic
    ' Start the service.
    Protected Overrides Sub OnStart(ByVal args() As String)
        Dim handle As IntPtr = Me.ServiceHandle
        myServiceStatus.currentState = Fix(State.SERVICE_START_PENDING)
        SetServiceStatus(handle, myServiceStatus)

        ' Start a separate thread that does the actual work.
        If workerThread Is Nothing OrElse (workerThread.ThreadState And System.Threading.ThreadState.Unstarted Or System.Threading.ThreadState.Stopped) <> 0 Then
#If LOGEVENTS Then
            System.Diagnostics.EventLog.WriteEntry("SimpleService.OnStart", DateTime.Now.ToLongTimeString() + _
                " - Starting the service worker thread.")
#End If

            workerThread = New Thread(New ThreadStart(AddressOf ServiceWorkerMethod))
            workerThread.Start()
        End If
        If Not (workerThread Is Nothing) Then
#If LOGEVENTS Then
            System.Diagnostics.EventLog.WriteEntry("SimpleService.OnStart", DateTime.Now.ToLongTimeString() + _
                " - Worker thread state = " + workerThread.ThreadState.ToString())
#End If
        End If
        myServiceStatus.currentState = Fix(State.SERVICE_RUNNING)
        SetServiceStatus(handle, myServiceStatus)

    End Sub 'OnStart
C#
        // Start the service.
        protected override void OnStart(string[] args)
        {
            IntPtr handle = this.ServiceHandle;
            myServiceStatus.currentState = (int)State.SERVICE_START_PENDING;
            SetServiceStatus(handle, myServiceStatus);

            // Start a separate thread that does the actual work.

            if ((workerThread == null) ||
                ((workerThread.ThreadState &
                 (System.Threading.ThreadState.Unstarted | System.Threading.ThreadState.Stopped)) != 0))
            {
#if LOGEVENTS
                EventLog.WriteEntry("SimpleService.OnStart", DateTime.Now.ToLongTimeString() +
                    " - Starting the service worker thread.");
#endif

                workerThread = new Thread(new ThreadStart(ServiceWorkerMethod));
                workerThread.Start();
            }
            if (workerThread != null)
            {
#if LOGEVENTS
                EventLog.WriteEntry("SimpleService.OnStart", DateTime.Now.ToLongTimeString() +
                    " - Worker thread state = " +
                    workerThread.ThreadState.ToString());
#endif
            }
            myServiceStatus.currentState = (int)State.SERVICE_RUNNING;
            SetServiceStatus(handle, myServiceStatus);

        }

Windows 98, Windows 2000 Service Pack 4, Windows Millennium, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter

Microsoft .NET Framework 3.0 es compatible con Windows Vista, Microsoft Windows XP SP2 y Windows Server 2003 SP1.

.NET Framework

Compatible con: 3.0, 2.0, 1.1, 1.0
© 2009 Microsoft Corporation. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker