Thread.Start Método

Definição

Faz com que um thread seja agendado para execução.Causes a thread to be scheduled for execution.

Sobrecargas

Start()

Faz com que o sistema operacional altere o estado da instância atual para Running.Causes the operating system to change the state of the current instance to Running.

Start(Object)

Faz com que o sistema operacional altere o estado da instância atual para Running e, opcionalmente, fornece um objeto que contém dados a serem usados pelo método executado pelo thread.Causes the operating system to change the state of the current instance to Running, and optionally supplies an object containing data to be used by the method the thread executes.

Start()

Faz com que o sistema operacional altere o estado da instância atual para Running.Causes the operating system to change the state of the current instance to Running.

public:
 void Start();
public void Start ();
member this.Start : unit -> unit
Public Sub Start ()

Exceções

O thread já foi iniciado.The thread has already been started.

Não há memória suficiente disponível para iniciar esse thread.There is not enough memory available to start this thread.

Exemplos

O exemplo a seguir cria e inicia um thread.The following example creates and starts a thread.

using namespace System;
using namespace System::Threading;

public ref class ThreadWork
{
public:
   static void DoWork()
   {
      for ( int i = 0; i < 3; i++ )
      {
         Console::WriteLine( "Working thread..." );
         Thread::Sleep( 100 );
      }
   }
};

int main()
{
   ThreadStart^ myThreadDelegate = gcnew ThreadStart(&ThreadWork::DoWork);
   Thread^ thread1 = gcnew Thread( myThreadDelegate );
   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...
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...
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...

Comentários

Quando um thread está no estado ThreadState.Running, o sistema operacional pode agendá-lo para execução.Once a thread is in the ThreadState.Running state, the operating system can schedule it for execution. O thread começa a ser executado na primeira linha do método representado pelo delegado ThreadStart ou ParameterizedThreadStart fornecido ao construtor de thread.The thread begins executing at the first line of the method represented by the ThreadStart or ParameterizedThreadStart delegate supplied to the thread constructor. Observe que a chamada para Start não bloqueia o thread de chamada.Note that the call to Start does not block the calling thread.

Observação

Se essa sobrecarga for usada com um thread criado usando um delegado ParameterizedThreadStart, null será passado para o método executado pelo thread.If this overload is used with a thread created using a ParameterizedThreadStart delegate, null is passed to the method executed by the thread.

Depois que o thread for encerrado, ele não poderá ser reiniciado com outra chamada para Start.Once the thread terminates, it cannot be restarted with another call to Start.

Veja também

Start(Object)

Faz com que o sistema operacional altere o estado da instância atual para Running e, opcionalmente, fornece um objeto que contém dados a serem usados pelo método executado pelo thread.Causes the operating system to change the state of the current instance to Running, and optionally supplies an object containing data to be used by the method the thread executes.

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

Um objeto que contém dados a serem usados pelo método executado pelo thread.An object that contains data to be used by the method the thread executes.

Exceções

O thread já foi iniciado.The thread has already been started.

Não há memória suficiente disponível para iniciar esse thread.There is not enough memory available to start this thread.

Esse thread foi criado usando um delegado ThreadStart em vez de um delegado ParameterizedThreadStart.This thread was created using a ThreadStart delegate instead of a ParameterizedThreadStart delegate.

Exemplos

O exemplo a seguir cria um delegado ParameterizedThreadStart com um método estático e um método de instância.The following example creates a ParameterizedThreadStart delegate with a static method and an instance method.

using namespace System;
using namespace System::Threading;

namespace SystemThreadingExample
{
    public ref class Work
    {
    public:
        void StartThreads()
        {
            // Start a thread that calls a parameterized static method.
            Thread^ newThread = gcnew
                Thread(gcnew ParameterizedThreadStart(Work::DoWork));
            newThread->Start(42);
              
            // Start a thread that calls a parameterized instance method.
            Work^ someWork = gcnew Work;
            newThread = gcnew Thread(
                        gcnew ParameterizedThreadStart(someWork,
                        &Work::DoMoreWork));
            newThread->Start("The answer.");
        }

        static void DoWork(Object^ data)
        {
            Console::WriteLine("Static thread procedure. Data='{0}'", 
                data);
        }

        void DoMoreWork(Object^ data)
        {
            Console::WriteLine("Instance thread procedure. Data='{0}'", 
                data);
        }
    };
}

//Entry point of example application
int main()
{
    SystemThreadingExample::Work^ samplework = 
        gcnew SystemThreadingExample::Work();
    samplework->StartThreads();
}
// This example displays output like the following:
//       Static thread procedure. Data='42'
//       Instance thread procedure. Data='The answer.'
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.'
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.'

Comentários

Quando um thread está no estado ThreadState.Running, o sistema operacional pode agendá-lo para execução.Once a thread is in the ThreadState.Running state, the operating system can schedule it for execution. O thread começa a ser executado na primeira linha do método representado pelo delegado ThreadStart ou ParameterizedThreadStart fornecido ao construtor de thread.The thread begins executing at the first line of the method represented by the ThreadStart or ParameterizedThreadStart delegate supplied to the thread constructor. Observe que a chamada para Start não bloqueia o thread de chamada.Note that the call to Start does not block the calling thread.

Depois que o thread for encerrado, ele não poderá ser reiniciado com outra chamada para Start.Once the thread terminates, it cannot be restarted with another call to Start.

Essa sobrecarga e o delegado ParameterizedThreadStart facilitam a passagem de dados para um procedimento de thread, mas a técnica não é de tipo seguro porque qualquer objeto pode ser passado para essa sobrecarga.This overload and the ParameterizedThreadStart delegate make it easy to pass data to a thread procedure, but the technique is not type safe because any object can be passed to this overload. Uma maneira mais robusta de passar dados para um procedimento de thread é colocar o procedimento de thread e os campos de dados em um objeto de trabalho.A more robust way to pass data to a thread procedure is to put both the thread procedure and the data fields into a worker object. Para obter mais informações, consulte criando threads e passando dados na hora de início.For more information, see Creating Threads and Passing Data at Start Time.

Veja também

Aplica-se a