Control.Invoke Método

Definición

Ejecuta un delegado en el subproceso que posee el identificador de ventana subyacente del control.

Sobrecargas

Invoke(Action)

Ejecuta el delegado especificado en el subproceso que posee el identificador de ventana subyacente del control.

Invoke(Delegate)

Ejecuta el delegado especificado en el subproceso que posee el identificador de ventana subyacente del control.

Invoke(Delegate, Object[])

Ejecuta el delegado especificado en el subproceso que posee el identificador de la ventana subyacente del control, con la lista de argumentos especificada.

Invoke<T>(Func<T>)

Ejecuta el delegado especificado en el subproceso que posee el identificador de ventana subyacente del control.

Invoke(Action)

Ejecuta el delegado especificado en el subproceso que posee el identificador de ventana subyacente del control.

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

Parámetros

method
Action

Delegado que contiene un método al que se va a llamar en el contexto del subproceso del control.

Se aplica a

Invoke(Delegate)

Ejecuta el delegado especificado en el subproceso que posee el identificador de ventana subyacente del control.

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

Parámetros

method
Delegate

Delegado que contiene un método al que se va a llamar en el contexto del subproceso del control.

Devoluciones

Valor devuelto desde el delegado al que se ha invocado o null si el delegado no devuelve ningún valor.

Ejemplos

En el ejemplo de código siguiente se muestran los controles que contienen un delegado. El delegado encapsula un método que agrega elementos al cuadro de lista y este método se ejecuta en el subproceso que posee el identificador subyacente del formulario. Cuando el usuario hace clic en el botón, Invoke ejecuta el delegado.

/*
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

Comentarios

Los delegados son similares a los punteros de función en lenguajes C o C++. Delega una referencia a un método dentro de un objeto delegado. A continuación, el objeto delegado se puede pasar al código que llama al método al que se hace referencia y el método al que se va a invocar puede ser desconocido en tiempo de compilación. A diferencia de los punteros de función en C o C++, los delegados están orientados a objetos, seguros para tipos y son más seguros.

El Invoke método busca en la cadena primaria del control hasta que encuentre un control o formulario que tenga un identificador de ventana si el identificador de ventana subyacente del control actual aún no existe. Si no se encuentra ningún identificador adecuado, el Invoke método producirá una excepción. Las excepciones que se producen durante la llamada se propagarán al autor de la llamada.

Nota

Además de la InvokeRequired propiedad , hay cuatro métodos en un control que son seguros para subprocesos: Invoke, BeginInvoke, EndInvokey CreateGraphics si el identificador del control ya se ha creado. Llamar CreateGraphics a antes de que se haya creado el identificador del control en un subproceso en segundo plano puede provocar llamadas entre subprocesos no válidas. Para todas las demás llamadas de método, debe usar uno de los métodos de invocación para serializar la llamada al subproceso del control.

El delegado puede ser una instancia de EventHandler, en cuyo caso el parámetro sender contendrá este control y el parámetro de evento contendrá EventArgs.Empty. El delegado también puede ser una instancia de MethodInvokero cualquier otro delegado que tome una lista de parámetros void. Una llamada a un EventHandler delegado o MethodInvoker será más rápida que una llamada a otro tipo de delegado.

Nota

Se podría producir una excepción si el subproceso que debe procesar el mensaje ya no está activo.

Consulte también

Se aplica a

Invoke(Delegate, Object[])

Ejecuta el delegado especificado en el subproceso que posee el identificador de la ventana subyacente del control, con la lista de argumentos especificada.

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

Parámetros

method
Delegate

Delegado de un método que obtiene los parámetros del mismo número y tipo que los incluidos en el parámetro args.

args
Object[]

Matriz de objetos cuyos valores se pasan como argumentos al método especificado. Este parámetro puede ser null si el método no toma ningún argumento.

Devoluciones

Object que contiene el valor devuelto por el delegado al que se ha invocado, o null si el delegado no devuelve ningún valor.

Implementaciones

Ejemplos

En el ejemplo de código siguiente se muestran los controles que contienen un delegado. El delegado encapsula un método que agrega elementos al cuadro de lista y este método se ejecuta en el subproceso que posee el identificador subyacente del formulario, utilizando los argumentos especificados. Cuando el usuario hace clic en el botón, Invoke ejecuta el delegado.

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

Comentarios

Los delegados son similares a los punteros de función en lenguajes C o C++. Delega una referencia a un método dentro de un objeto delegado. A continuación, el objeto delegado se puede pasar al código que llama al método al que se hace referencia y el método al que se va a invocar puede ser desconocido en tiempo de compilación. A diferencia de los punteros de función en C o C++, los delegados están orientados a objetos, seguros para tipos y son más seguros.

Si el identificador del control aún no existe, este método busca en la cadena primaria del control hasta que encuentre un control o formulario que tenga un identificador de ventana. Si no se encuentra ningún identificador adecuado, este método produce una excepción. Las excepciones que se producen durante la llamada se propagarán al autor de la llamada.

Nota

Además de la InvokeRequired propiedad , hay cuatro métodos en un control que son seguros para subprocesos: Invoke, BeginInvoke, EndInvokey CreateGraphics si el identificador del control ya se ha creado. Llamar CreateGraphics a antes de que se haya creado el identificador del control en un subproceso en segundo plano puede provocar llamadas entre subprocesos no válidas. Para todas las demás llamadas de método, debe usar uno de los métodos de invocación para serializar la llamada al subproceso del control.

El delegado puede ser una instancia de EventHandler, en cuyo caso el parámetro sender contendrá este control y el parámetro de evento contendrá EventArgs.Empty. El delegado también puede ser una instancia de MethodInvokero cualquier otro delegado que tome una lista de parámetros void. Una llamada a un EventHandler delegado o MethodInvoker será más rápida que una llamada a otro tipo de delegado.

Nota

Se podría producir una excepción si el subproceso que debe procesar el mensaje ya no está activo.

Consulte también

Se aplica a

Invoke<T>(Func<T>)

Ejecuta el delegado especificado en el subproceso que posee el identificador de ventana subyacente del control.

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

Parámetros de tipo

T

Tipo de valor devuelto de method.

Parámetros

method
Func<T>

Función a la que se llamará en el contexto del subproceso del control.

Devoluciones

T

Valor devuelto de la función que se invoca.

Se aplica a