Control.Invoke Metodo

Definizione

Esegue un delegato nel thread proprietario del punto di controllo di finestra sottostante del controllo.

Overload

Invoke(Action)

Esegue il delegato specificato nel thread proprietario del punto di controllo di finestra sottostante del controllo.

Invoke(Delegate)

Esegue il delegato specificato nel thread proprietario del punto di controllo di finestra sottostante del controllo.

Invoke(Delegate, Object[])

Esegue il delegato specificato nel thread proprietario del punto di controllo di finestra sottostante del controllo con l'elenco di argomenti specificato.

Invoke<T>(Func<T>)

Esegue il delegato specificato nel thread proprietario del punto di controllo di finestra sottostante del controllo.

Invoke(Action)

Esegue il delegato specificato nel thread proprietario del punto di controllo di finestra sottostante del controllo.

public:
 void Invoke(Action ^ method);
public void Invoke (Action method);
member this.Invoke : Action -> unit
Public Sub Invoke (method As Action)

Parametri

method
Action

Delegato che contiene un metodo da chiamare nel contesto del thread del controllo.

Si applica a

Invoke(Delegate)

Esegue il delegato specificato nel thread proprietario del punto di controllo di finestra sottostante del controllo.

public:
 System::Object ^ Invoke(Delegate ^ method);
public object Invoke (Delegate method);
member this.Invoke : Delegate -> obj
Public Function Invoke (method As Delegate) As Object

Parametri

method
Delegate

Delegato che contiene un metodo da chiamare nel contesto del thread del controllo.

Restituisce

Valore restituito dal delegato richiamato oppure null se il delegato non restituisce alcun valore.

Esempio

Nell'esempio di codice seguente vengono illustrati i controlli che contengono un delegato. Il delegato incapsula un metodo che aggiunge elementi alla casella di riepilogo e questo metodo viene eseguito nel thread proprietario dell'handle sottostante del modulo. Quando l'utente fa clic sul pulsante, Invoke esegue il delegato.

/*
The following example demonstrates the 'Invoke(Delegate*)' method of 'Control class.
A 'ListBox' and a 'Button' control are added to a form, containing a delegate
which encapsulates a method that adds items to the listbox. This function is executed
on the thread that owns the underlying handle of the form. When user clicks on button
the above delegate is executed using 'Invoke' method.
*/

#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
using namespace System::Threading;

public ref class MyFormControl: public Form
{
public:
   delegate void AddListItem();
   AddListItem^ myDelegate;

private:
   Button^ myButton;
   Thread^ myThread;
   ListBox^ myListBox;

public:
   MyFormControl();
   void AddListItemMethod()
   {
      String^ myItem;
      for ( int i = 1; i < 6; i++ )
      {
         myItem = "MyListItem {0}",i;
         myListBox->Items->Add( myItem );
         myListBox->Update();
         Thread::Sleep( 300 );
      }
   }

private:
   void Button_Click( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      myThread = gcnew Thread( gcnew ThreadStart( this, &MyFormControl::ThreadFunction ) );
      myThread->Start();
   }

   void ThreadFunction();
};


// The following code assumes a 'ListBox' and a 'Button' control are added to a form,
// containing a delegate which encapsulates a method that adds items to the listbox.
public ref class MyThreadClass
{
private:
   MyFormControl^ myFormControl1;

public:
   MyThreadClass( MyFormControl^ myForm )
   {
      myFormControl1 = myForm;
   }

   void Run()
   {
      // Execute the specified delegate on the thread that owns
      // 'myFormControl1' control's underlying window handle.
      myFormControl1->Invoke( myFormControl1->myDelegate );
   }
};


MyFormControl::MyFormControl()
{
   myButton = gcnew Button;
   myListBox = gcnew ListBox;
   myButton->Location = Point( 72, 160 );
   myButton->Size = System::Drawing::Size( 152, 32 );
   myButton->TabIndex = 1;
   myButton->Text = "Add items in list box";
   myButton->Click += gcnew EventHandler( this, &MyFormControl::Button_Click );
   myListBox->Location = Point( 48, 32 );
   myListBox->Name = "myListBox";
   myListBox->Size = System::Drawing::Size( 200, 95 );
   myListBox->TabIndex = 2;
   ClientSize = System::Drawing::Size( 292, 273 );
   array<Control^>^ temp0 = {myListBox,myButton};
   Controls->AddRange( temp0 );
   Text = " 'Control_Invoke' example";
   myDelegate = gcnew AddListItem( this, &MyFormControl::AddListItemMethod );
}

void MyFormControl::ThreadFunction()
{
   MyThreadClass^ myThreadClassObject = gcnew MyThreadClass( this );
   myThreadClassObject->Run();
}

int main()
{
   MyFormControl^ myForm = gcnew MyFormControl;
   myForm->ShowDialog();
}
/*
The following example demonstrates the 'Invoke(Delegate)' method of 'Control class.
A 'ListBox' and a 'Button' control are added to a form, containing a delegate
which encapsulates a method that adds items to the listbox. This function is executed
on the thread that owns the underlying handle of the form. When user clicks on button
the above delegate is executed using 'Invoke' method.


*/

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;

   public class MyFormControl : Form
   {
      public delegate void AddListItem();
      public AddListItem myDelegate;
      private Button myButton;
      private Thread myThread;
      private ListBox myListBox;
      public MyFormControl()
      {
         myButton = new Button();
         myListBox = new ListBox();
         myButton.Location = new Point(72, 160);
         myButton.Size = new Size(152, 32);
         myButton.TabIndex = 1;
         myButton.Text = "Add items in list box";
         myButton.Click += new EventHandler(Button_Click);
         myListBox.Location = new Point(48, 32);
         myListBox.Name = "myListBox";
         myListBox.Size = new Size(200, 95);
         myListBox.TabIndex = 2;
         ClientSize = new Size(292, 273);
         Controls.AddRange(new Control[] {myListBox,myButton});
         Text = " 'Control_Invoke' example";
         myDelegate = new AddListItem(AddListItemMethod);
      }
      static void Main()
      {
         MyFormControl myForm = new MyFormControl();
         myForm.ShowDialog();
      }
      public void AddListItemMethod()
      {
         String myItem;
         for(int i=1;i<6;i++)
         {
            myItem = "MyListItem" + i.ToString();
            myListBox.Items.Add(myItem);
            myListBox.Update();
            Thread.Sleep(300);
         }
      }
      private void Button_Click(object sender, EventArgs e)
      {
         myThread = new Thread(new ThreadStart(ThreadFunction));
         myThread.Start();
      }
      private void ThreadFunction()
      {
         MyThreadClass myThreadClassObject  = new MyThreadClass(this);
         myThreadClassObject.Run();
      }
   }

// The following code assumes a 'ListBox' and a 'Button' control are added to a form, 
// containing a delegate which encapsulates a method that adds items to the listbox.

   public class MyThreadClass
   {
      MyFormControl myFormControl1;
      public MyThreadClass(MyFormControl myForm)
      {
         myFormControl1 = myForm;
      }

      public void Run()
      {
         // Execute the specified delegate on the thread that owns
         // 'myFormControl1' control's underlying window handle.
         myFormControl1.Invoke(myFormControl1.myDelegate);
      }
   }
' The following example demonstrates the 'Invoke(Delegate)' method of 'Control class.
' A 'ListBox' and a 'Button' control are added to a form, containing a delegate
' which encapsulates a method that adds items to the listbox. This function is executed
' on the thread that owns the underlying handle of the form. When user clicks on button
' the above delegate is executed using 'Invoke' method.

Imports System.Drawing
Imports System.Windows.Forms
Imports System.Threading

Public Class MyFormControl
   Inherits Form

   Delegate Sub AddListItem()
   Public myDelegate As AddListItem
   Private myButton As Button
   Private myThread As Thread
   Private myListBox As ListBox

   Public Sub New()
      myButton = New Button()
      myListBox = New ListBox()
      myButton.Location = New Point(72, 160)
      myButton.Size = New Size(152, 32)
      myButton.TabIndex = 1
      myButton.Text = "Add items in list box"
      AddHandler myButton.Click, AddressOf Button_Click
      myListBox.Location = New Point(48, 32)
      myListBox.Name = "myListBox"
      myListBox.Size = New Size(200, 95)
      myListBox.TabIndex = 2
      ClientSize = New Size(292, 273)
      Controls.AddRange(New Control() {myListBox, myButton})
      Text = " 'Control_Invoke' example"
      myDelegate = New AddListItem(AddressOf AddListItemMethod)
   End Sub

   Shared Sub Main()
      Dim myForm As New MyFormControl()
      myForm.ShowDialog()
   End Sub

   Public Sub AddListItemMethod()
      Dim myItem As String
      Dim i As Integer
      For i = 1 To 5
         myItem = "MyListItem" + i.ToString()
         myListBox.Items.Add(myItem)
         myListBox.Update()
         Thread.Sleep(300)
      Next i
   End Sub

   Private Sub Button_Click(sender As Object, e As EventArgs)
      myThread = New Thread(New ThreadStart(AddressOf ThreadFunction))
      myThread.Start()
   End Sub

   Private Sub ThreadFunction()
      Dim myThreadClassObject As New MyThreadClass(Me)
      myThreadClassObject.Run()
   End Sub
End Class


' The following code assumes a 'ListBox' and a 'Button' control are added to a form, 
' containing a delegate which encapsulates a method that adds items to the listbox.
Public Class MyThreadClass
   Private myFormControl1 As MyFormControl

   Public Sub New(myForm As MyFormControl)
      myFormControl1 = myForm
   End Sub

   Public Sub Run()
      ' Execute the specified delegate on the thread that owns
      ' 'myFormControl1' control's underlying window handle.
      myFormControl1.Invoke(myFormControl1.myDelegate)
   End Sub

End Class

Commenti

I delegati sono simili ai puntatori alle funzioni nei linguaggi C o C++. I delegati incapsulano un riferimento a un metodo all'interno di un oggetto delegato. L'oggetto delegato può quindi essere passato al codice che chiama il metodo a cui fa riferimento e il metodo da richiamare può essere sconosciuto in fase di compilazione. A differenza dei puntatori a funzioni in C o C++, i delegati sono orientati a oggetti, sicuri per il tipo e più sicuri.

Il Invoke metodo cerca la catena padre del controllo finché non trova un controllo o una maschera con un handle di finestra se l'handle della finestra sottostante del controllo corrente non esiste ancora. Se non è possibile trovare alcun handle appropriato, il metodo genererà un'eccezione Invoke . Le eccezioni generate durante la chiamata verranno propagate nuovamente al chiamante.

Nota

Oltre alla InvokeRequired proprietà, sono disponibili quattro metodi su un controllo thread safe: Invoke, BeginInvoke, EndInvokee CreateGraphics se l'handle per il controllo è già stato creato. La chiamata CreateGraphics prima della creazione dell'handle del controllo in un thread in background può causare chiamate tra thread non valide. Per tutte le altre chiamate di metodo, è consigliabile usare uno dei metodi invoke per eseguire il marshalling della chiamata al thread del controllo.

Il delegato può essere un'istanza di EventHandler, nel qual caso il parametro del mittente conterrà questo controllo e il parametro evento conterrà EventArgs.Empty. Il delegato può anche essere un'istanza di MethodInvokero qualsiasi altro delegato che accetta un elenco di parametri void. Una chiamata a un delegato o MethodInvoker sarà più veloce di una EventHandler chiamata a un altro tipo di delegato.

Nota

Un'eccezione potrebbe essere generata se il thread che deve elaborare il messaggio non è più attivo.

Vedi anche

Si applica a

Invoke(Delegate, Object[])

Esegue il delegato specificato nel thread proprietario del punto di controllo di finestra sottostante del controllo con l'elenco di argomenti specificato.

public:
 virtual System::Object ^ Invoke(Delegate ^ method, cli::array <System::Object ^> ^ args);
public:
 virtual System::Object ^ Invoke(Delegate ^ method, ... cli::array <System::Object ^> ^ args);
public object Invoke (Delegate method, object[] args);
public object Invoke (Delegate method, params object[] args);
public object Invoke (Delegate method, params object?[]? args);
abstract member Invoke : Delegate * obj[] -> obj
override this.Invoke : Delegate * obj[] -> obj
Public Function Invoke (method As Delegate, args As Object()) As Object
Public Function Invoke (method As Delegate, ParamArray args As Object()) As Object

Parametri

method
Delegate

Delegato di un metodo che accetta parametri dello stesso tipo e numero contenuti nel parametro args.

args
Object[]

Matrice di oggetti da passare come argomenti al metodo specificato. Se il metodo non accetta alcun argomento, questo parametro può essere null.

Restituisce

Oggetto Object che contiene il valore restituito dal delegato richiamato oppure null se il delegato non restituisce alcun valore.

Implementazioni

Esempio

Nell'esempio di codice seguente vengono illustrati i controlli che contengono un delegato. Il delegato incapsula un metodo che aggiunge elementi alla casella di riepilogo e questo metodo viene eseguito nel thread che possiede l'handle sottostante del modulo usando gli argomenti specificati. Quando l'utente fa clic sul pulsante, Invoke esegue il delegato.

using namespace System;
using namespace System::Drawing;
using namespace System::ComponentModel;
using namespace System::Windows::Forms;
using namespace System::Threading;
ref class MyFormControl: public Form
{
public:
   delegate void AddListItem( String^ myString );
   AddListItem^ myDelegate;

private:
   Button^ myButton;
   Thread^ myThread;
   ListBox^ myListBox;

public:
   MyFormControl();
   void AddListItemMethod( String^ myString );

private:
   void Button_Click( Object^ sender, EventArgs^ e );
   void ThreadFunction();
};

ref class MyThreadClass
{
private:
   MyFormControl^ myFormControl1;

public:
   MyThreadClass( MyFormControl^ myForm )
   {
      myFormControl1 = myForm;
   }

   String^ myString;
   void Run()
   {
      for ( int i = 1; i <= 5; i++ )
      {
         myString = String::Concat( "Step number ", i, " executed" );
         Thread::Sleep( 400 );
         
         // Execute the specified delegate on the thread that owns
         // 'myFormControl1' control's underlying window handle with
         // the specified list of arguments.
         array<Object^>^myStringArray = {myString};
         myFormControl1->Invoke( myFormControl1->myDelegate, myStringArray );

      }
   }

};

MyFormControl::MyFormControl()
{
   myButton = gcnew Button;
   myListBox = gcnew ListBox;
   myButton->Location = Point(72,160);
   myButton->Size = System::Drawing::Size( 152, 32 );
   myButton->TabIndex = 1;
   myButton->Text = "Add items in list box";
   myButton->Click += gcnew EventHandler( this, &MyFormControl::Button_Click );
   myListBox->Location = Point(48,32);
   myListBox->Name = "myListBox";
   myListBox->Size = System::Drawing::Size( 200, 95 );
   myListBox->TabIndex = 2;
   ClientSize = System::Drawing::Size( 292, 273 );
   array<Control^>^formControls = {myListBox,myButton};
   Controls->AddRange( formControls );
   Text = " 'Control_Invoke' example ";
   myDelegate = gcnew AddListItem( this, &MyFormControl::AddListItemMethod );
}

void MyFormControl::AddListItemMethod( String^ myString )
{
   myListBox->Items->Add( myString );
}

void MyFormControl::Button_Click( Object^ /*sender*/, EventArgs^ /*e*/ )
{
   myThread = gcnew Thread( gcnew ThreadStart( this, &MyFormControl::ThreadFunction ) );
   myThread->Start();
}

void MyFormControl::ThreadFunction()
{
   MyThreadClass^ myThreadClassObject = gcnew MyThreadClass( this );
   myThreadClassObject->Run();
}

int main()
{
   MyFormControl^ myForm = gcnew MyFormControl;
   myForm->ShowDialog();
}
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;

   public class MyFormControl : Form
   {
      public delegate void AddListItem(String myString);
      public AddListItem myDelegate;
      private Button myButton;
      private Thread myThread;
      private ListBox myListBox;
      public MyFormControl()
      {
         myButton = new Button();
         myListBox = new ListBox();
         myButton.Location = new Point(72, 160);
         myButton.Size = new Size(152, 32);
         myButton.TabIndex = 1;
         myButton.Text = "Add items in list box";
         myButton.Click += new EventHandler(Button_Click);
         myListBox.Location = new Point(48, 32);
         myListBox.Name = "myListBox";
         myListBox.Size = new Size(200, 95);
         myListBox.TabIndex = 2;
         ClientSize = new Size(292, 273);
         Controls.AddRange(new Control[] {myListBox,myButton});
         Text = " 'Control_Invoke' example ";
         myDelegate = new AddListItem(AddListItemMethod);
      }
      static void Main()
      {
         MyFormControl myForm = new MyFormControl();
         myForm.ShowDialog();
      }
      public void AddListItemMethod(String myString)
      {
            myListBox.Items.Add(myString);
      }
      private void Button_Click(object sender, EventArgs e)
      {
         myThread = new Thread(new ThreadStart(ThreadFunction));
         myThread.Start();
      }
      private void ThreadFunction()
      {
         MyThreadClass myThreadClassObject  = new MyThreadClass(this);
         myThreadClassObject.Run();
      }
   }
   public class MyThreadClass
   {
      MyFormControl myFormControl1;
      public MyThreadClass(MyFormControl myForm)
      {
         myFormControl1 = myForm;
      }
      String myString;

      public void Run()
      {

         for (int i = 1; i <= 5; i++)
         {
            myString = "Step number " + i.ToString() + " executed";
            Thread.Sleep(400);
            // Execute the specified delegate on the thread that owns
            // 'myFormControl1' control's underlying window handle with
            // the specified list of arguments.
            myFormControl1.Invoke(myFormControl1.myDelegate,
                                   new Object[] {myString});
         }
      }
   }
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Threading

Public Class MyFormControl
   Inherits Form

   Delegate Sub AddListItem(myString As String)
   Public myDelegate As AddListItem
   Private myButton As Button
   Private myThread As Thread
   Private myListBox As ListBox

   Public Sub New()
      myButton = New Button()
      myListBox = New ListBox()
      myButton.Location = New Point(72, 160)
      myButton.Size = New Size(152, 32)
      myButton.TabIndex = 1
      myButton.Text = "Add items in list box"
      AddHandler myButton.Click, AddressOf Button_Click
      myListBox.Location = New Point(48, 32)
      myListBox.Name = "myListBox"
      myListBox.Size = New Size(200, 95)
      myListBox.TabIndex = 2
      ClientSize = New Size(292, 273)
      Controls.AddRange(New Control() {myListBox, myButton})
      Text = " 'Control_Invoke' example "
      myDelegate = New AddListItem(AddressOf AddListItemMethod)
   End Sub

   Shared Sub Main()
      Dim myForm As New MyFormControl()
      myForm.ShowDialog()
   End Sub

   Public Sub AddListItemMethod(myString As String)
      myListBox.Items.Add(myString)
   End Sub

   Private Sub Button_Click(sender As Object, e As EventArgs)
      myThread = New Thread(New ThreadStart(AddressOf ThreadFunction))
      myThread.Start()
   End Sub

   Private Sub ThreadFunction()
      Dim myThreadClassObject As New MyThreadClass(Me)
      myThreadClassObject.Run()
   End Sub
End Class

Public Class MyThreadClass
   Private myFormControl1 As MyFormControl

   Public Sub New(myForm As MyFormControl)
      myFormControl1 = myForm
   End Sub
   Private myString As String

   Public Sub Run()

      Dim i As Integer
      For i = 1 To 5
         myString = "Step number " + i.ToString() + " executed"
         Thread.Sleep(400)
         ' Execute the specified delegate on the thread that owns
         ' 'myFormControl1' control's underlying window handle with
         ' the specified list of arguments.
         myFormControl1.Invoke(myFormControl1.myDelegate, New Object() {myString})
      Next i

   End Sub
End Class

Commenti

I delegati sono simili ai puntatori alle funzioni nei linguaggi C o C++. I delegati incapsulano un riferimento a un metodo all'interno di un oggetto delegato. L'oggetto delegato può quindi essere passato al codice che chiama il metodo a cui fa riferimento e il metodo da richiamare può essere sconosciuto in fase di compilazione. A differenza dei puntatori a funzioni in C o C++, i delegati sono orientati a oggetti, sicuri per il tipo e più sicuri.

Se l'handle del controllo non esiste ancora, questo metodo esegue la ricerca della catena padre del controllo fino a quando non trova un controllo o una maschera che dispone di un handle di finestra. Se non è possibile trovare alcun handle appropriato, questo metodo genera un'eccezione. Le eccezioni generate durante la chiamata verranno propagate nuovamente al chiamante.

Nota

Oltre alla InvokeRequired proprietà, sono disponibili quattro metodi su un controllo thread safe: Invoke, BeginInvoke, EndInvokee CreateGraphics se l'handle per il controllo è già stato creato. La chiamata CreateGraphics prima della creazione dell'handle del controllo in un thread in background può causare chiamate tra thread non valide. Per tutte le altre chiamate di metodo, è consigliabile usare uno dei metodi invoke per eseguire il marshalling della chiamata al thread del controllo.

Il delegato può essere un'istanza di EventHandler, nel qual caso il parametro del mittente conterrà questo controllo e il parametro evento conterrà EventArgs.Empty. Il delegato può anche essere un'istanza di MethodInvokero qualsiasi altro delegato che accetta un elenco di parametri void. Una chiamata a un delegato o MethodInvoker sarà più veloce di una EventHandler chiamata a un altro tipo di delegato.

Nota

Un'eccezione potrebbe essere generata se il thread che deve elaborare il messaggio non è più attivo.

Vedi anche

Si applica a

Invoke<T>(Func<T>)

Esegue il delegato specificato nel thread proprietario del punto di controllo di finestra sottostante del controllo.

public:
generic <typename T>
 T Invoke(Func<T> ^ method);
public T Invoke<T> (Func<T> method);
member this.Invoke : Func<'T> -> 'T
Public Function Invoke(Of T) (method As Func(Of T)) As T

Parametri di tipo

T

Tipo restituito di method.

Parametri

method
Func<T>

Funzione da chiamare nel contesto del thread del controllo.

Restituisce

T

Valore restituito dalla funzione richiamata.

Si applica a