Thread.Start Método
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Hace que un subproceso se programe para su ejecución.
Sobrecargas
| Nombre | Description |
|---|---|
| Start() |
Hace que el sistema operativo cambie el estado de la instancia actual a Running. |
| Start(Object) |
Hace que el sistema operativo cambie el estado de la instancia actual a Runningy, opcionalmente, proporciona un objeto que contiene datos que el método ejecuta el subproceso. |
Start()
Hace que el sistema operativo cambie el estado de la instancia actual a Running.
public:
void Start();
public void Start();
member this.Start : unit -> unit
Public Sub Start ()
Excepciones
El subproceso ya se ha iniciado.
No hay suficiente memoria disponible para iniciar este subproceso.
Ejemplos
En el ejemplo siguiente se crea e inicia un subproceso.
using System;
using System.Threading;
public class ThreadWork
{
public static void DoWork()
{
for(int i = 0; i<3;i++) {
Console.WriteLine("Working thread...");
Thread.Sleep(100);
}
}
}
class ThreadTest
{
public static void Main()
{
Thread thread1 = new Thread(ThreadWork.DoWork);
thread1.Start();
for (int i = 0; i<3; i++) {
Console.WriteLine("In main.");
Thread.Sleep(100);
}
}
}
// The example displays output like the following:
// In main.
// Working thread...
// In main.
// Working thread...
// In main.
// Working thread...
open System.Threading
module ThreadWork =
let doWork () =
for _ = 0 to 2 do
printfn "Working thread..."
Thread.Sleep 100
let thread1 = Thread ThreadWork.doWork
thread1.Start()
for _ = 0 to 2 do
printfn "In main."
Thread.Sleep 100
// The example displays output like the following:
// In main.
// Working thread...
// In main.
// Working thread...
// In main.
// Working thread...
Imports System.Threading
Public Class ThreadWork
Public Shared Sub DoWork()
Dim i As Integer
For i = 0 To 2
Console.WriteLine("Working thread...")
Thread.Sleep(100)
Next i
End Sub
End Class
Class ThreadTest
Public Shared Sub Main()
Dim thread1 As New Thread(AddressOf ThreadWork.DoWork)
thread1.Start()
Dim i As Integer
For i = 0 To 2
Console.WriteLine("In main.")
Thread.Sleep(100)
Next
End Sub
End Class
' The example displays output like the following:
' In main.
' Working thread...
' In main.
' Working thread...
' In main.
' Working thread...
Comentarios
Una vez que un subproceso está en estado ThreadState.Running , el sistema operativo puede programarlo para su ejecución. El subproceso comienza a ejecutarse en la primera línea del método representado por el ThreadStart delegado o ParameterizedThreadStart proporcionado al constructor de subprocesos. Tenga en cuenta que la llamada a Start no bloquea el subproceso que realiza la llamada.
Note
Si esta sobrecarga se usa con un subproceso creado mediante un ParameterizedThreadStart delegado, null se pasa al método ejecutado por el subproceso.
Una vez finalizado el subproceso, no se puede reiniciar con otra llamada a Start.
Consulte también
Se aplica a
Start(Object)
Hace que el sistema operativo cambie el estado de la instancia actual a Runningy, opcionalmente, proporciona un objeto que contiene datos que el método ejecuta el subproceso.
public:
void Start(System::Object ^ parameter);
public void Start(object parameter);
member this.Start : obj -> unit
Public Sub Start (parameter As Object)
Parámetros
- parameter
- Object
Objeto que contiene los datos que va a usar el método que ejecuta el subproceso.
Excepciones
El subproceso ya se ha iniciado.
No hay suficiente memoria disponible para iniciar este subproceso.
Este subproceso se creó mediante un ThreadStart delegado en lugar de un ParameterizedThreadStart delegado.
Ejemplos
En el ejemplo siguiente se crea un ParameterizedThreadStart delegado con un método estático y un método de instancia.
using System;
using System.Threading;
public class Work
{
public static void Main()
{
// Start a thread that calls a parameterized static method.
Thread newThread = new Thread(Work.DoWork);
newThread.Start(42);
// Start a thread that calls a parameterized instance method.
Work w = new Work();
newThread = new Thread(w.DoMoreWork);
newThread.Start("The answer.");
}
public static void DoWork(object data)
{
Console.WriteLine("Static thread procedure. Data='{0}'",
data);
}
public void DoMoreWork(object data)
{
Console.WriteLine("Instance thread procedure. Data='{0}'",
data);
}
}
// This example displays output like the following:
// Static thread procedure. Data='42'
// Instance thread procedure. Data='The answer.'
open System.Threading
type Work() =
static member DoWork(data: obj) =
printfn $"Static thread procedure. Data='{data}'"
member _.DoMoreWork(data: obj) =
printfn $"Instance thread procedure. Data='{data}'"
// Start a thread that calls a parameterized static method.
let newThread = Thread(ParameterizedThreadStart Work.DoWork)
newThread.Start 42
// Start a thread that calls a parameterized instance method.
let w = Work()
let newThread2 = Thread(ParameterizedThreadStart w.DoMoreWork)
newThread.Start "The answer."
// This example displays output like the following:
// Static thread procedure. Data='42'
// Instance thread procedure. Data='The answer.'
Imports System.Threading
Public Class Work
Shared Sub Main()
' Start a thread that calls a parameterized static method.
Dim newThread As New Thread(AddressOf Work.DoWork)
newThread.Start(42)
' Start a thread that calls a parameterized instance method.
Dim w As New Work()
newThread = New Thread(AddressOf w.DoMoreWork)
newThread.Start("The answer.")
End Sub
Public Shared Sub DoWork(ByVal data As Object)
Console.WriteLine("Static thread procedure. Data='{0}'",
data)
End Sub
Public Sub DoMoreWork(ByVal data As Object)
Console.WriteLine("Instance thread procedure. Data='{0}'",
data)
End Sub
End Class
' This example displays output like the following:
' Static thread procedure. Data='42'
' Instance thread procedure. Data='The answer.'
Comentarios
Una vez que un subproceso está en estado ThreadState.Running , el sistema operativo puede programarlo para su ejecución. El subproceso comienza a ejecutarse en la primera línea del método representado por el ThreadStart delegado o ParameterizedThreadStart proporcionado al constructor de subprocesos. Tenga en cuenta que la llamada a Start no bloquea el subproceso que realiza la llamada.
Una vez finalizado el subproceso, no se puede reiniciar con otra llamada a Start.
Esta sobrecarga y el ParameterizedThreadStart delegado facilitan el paso de datos a un procedimiento de subproceso, pero la técnica no es segura para tipos porque se puede pasar cualquier objeto a esta sobrecarga. Una manera más sólida de pasar datos a un procedimiento de subproceso es colocar tanto el procedimiento de subproceso como los campos de datos en un objeto de trabajo. Para obtener más información, vea Crear subprocesos y pasar datos a la hora de inicio.