Procedimiento Realizar llamadas seguras para subprocesos a controles de formularios Windows FormsHow to: Make thread-safe calls to Windows Forms controls

El multithreading puede mejorar el rendimiento de las aplicaciones de Windows Forms, pero el acceso a los controles de Windows Forms no es intrínsecamente seguro para subprocesos.Multithreading can improve the performance of Windows Forms apps, but access to Windows Forms controls isn't inherently thread-safe. El multithreading puede exponer el código de errores muy graves y complejos.Multithreading can expose your code to very serious and complex bugs. Dos o más subprocesos para manipular un control pueden forzar el control a un estado incoherente y conducir a condiciones de carrera, interbloqueos y se inmoviliza o se bloquea.Two or more threads manipulating a control can force the control into an inconsistent state and lead to race conditions, deadlocks, and freezes or hangs. Si implementa multithreading en la aplicación, asegúrese de llamar a los controles entre subprocesos de forma segura para subprocesos.If you implement multithreading in your app, be sure to call cross-thread controls in a thread-safe way. Para obtener más información, consulte Managed threading best practices.For more information, see Managed threading best practices.

Hay dos maneras de llamar con seguridad a un control de Windows Forms desde un subproceso que no ha creado ese control.There are two ways to safely call a Windows Forms control from a thread that didn't create that control. Puede usar el System.Windows.Forms.Control.Invoke método para llamar a un delegado que se crea en el subproceso principal, que a su vez llama al control.You can use the System.Windows.Forms.Control.Invoke method to call a delegate created in the main thread, which in turn calls the control. O bien, puede implementar un System.ComponentModel.BackgroundWorker, que utiliza un modelo orientado a eventos para separar el trabajo realizado en el subproceso en segundo plano de los informes en los resultados.Or, you can implement a System.ComponentModel.BackgroundWorker, which uses an event-driven model to separate work done in the background thread from reporting on the results.

Llamadas entre subprocesos no segurasUnsafe cross-thread calls

No es seguro llamar a un control directamente desde un subproceso que no crearla.It's unsafe to call a control directly from a thread that didn't create it. El fragmento de código siguiente muestra una llamada no segura para el System.Windows.Forms.TextBox control.The following code snippet illustrates an unsafe call to the System.Windows.Forms.TextBox control. El Button1_Click crea un nuevo controlador de eventos WriteTextUnsafe subproceso, que establece el subproceso principal TextBox.Text propiedad directamente.The Button1_Click event handler creates a new WriteTextUnsafe thread, which sets the main thread's TextBox.Text property directly.

private void Button1_Click(object sender, EventArgs e)
{
    thread2 = new Thread(new ThreadStart(WriteTextUnsafe));
    thread2.Start();
}
private void WriteTextUnsafe()
{
    textBox1.Text = "This text was set unsafely.";
}
Private Sub Button1_Click(ByVal sender As Object, e As EventArgs) Handles Button1.Click
    Thread2 = New Thread(New ThreadStart(AddressOf WriteTextUnsafe))
    Thread2.Start()
End Sub

Private Sub WriteTextUnsafe()
    TextBox1.Text = "This text was set unsafely."
End Sub

El depurador de Visual Studio detecta estas llamadas no seguras de subproceso generando una InvalidOperationException con el mensaje, operación entre subprocesos no es válida. Control "" acceso desde un subproceso distinto del subproceso que lo creó.The Visual Studio debugger detects these unsafe thread calls by raising an InvalidOperationException with the message, Cross-thread operation not valid. Control "" accessed from a thread other than the thread it was created on. El InvalidOperationException siempre se produce para las llamadas entre subprocesos no seguras durante la depuración de Visual Studio y puede producirse en tiempo de ejecución de aplicación.The InvalidOperationException always occurs for unsafe cross-thread calls during Visual Studio debugging, and may occur at app runtime. Debe corregir el problema, pero se puede deshabilitar la excepción estableciendo la Control.CheckForIllegalCrossThreadCalls propiedad false.You should fix the issue, but you can disable the exception by setting the Control.CheckForIllegalCrossThreadCalls property to false.

Llamadas entre subprocesos segurasSafe cross-thread calls

Los ejemplos de código siguiente muestran dos maneras de llamar con seguridad a un control de Windows Forms desde un subproceso que no crearla:The following code examples demonstrate two ways to safely call a Windows Forms control from a thread that didn't create it:

  1. El System.Windows.Forms.Control.Invoke método, que llama a un delegado desde el subproceso principal para el control de llamadas.The System.Windows.Forms.Control.Invoke method, which calls a delegate from the main thread to call the control.
  2. Un System.ComponentModel.BackgroundWorker componente, que ofrece un modelo orientado a eventos.A System.ComponentModel.BackgroundWorker component, which offers an event-driven model.

En ambos ejemplos, el subproceso de fondo se suspende durante un segundo simular el trabajo que se realiza en ese subproceso.In both examples, the background thread sleeps for one second to simulate work being done in that thread.

Puede compilar y ejecutar estos ejemplos como aplicaciones de .NET Framework desde el C# o línea de comandos de Visual Basic.You can build and run these examples as .NET Framework apps from the C# or Visual Basic command line. Para obtener más información, consulte de línea de comandos para compilar con csc.exe o construido a partir de la línea de comandos (Visual Basic).For more information, see Command-line building with csc.exe or Build from the command line (Visual Basic).

A partir de .NET Core 3.0, también puede compilar y ejecutar los ejemplos como aplicaciones de .NET Core de Windows desde una carpeta que tenga un núcleo de .NET Windows Forms <nombre de carpeta > .csproj archivo de proyecto.Starting with .NET Core 3.0, you can also build and run the examples as Windows .NET Core apps from a folder that has a .NET Core Windows Forms <folder name>.csproj project file.

Ejemplo: Utilice el método de invocación con un delegadoExample: Use the Invoke method with a delegate

El ejemplo siguiente muestra un patrón para garantizar las llamadas de subprocesos a un control de Windows Forms.The following example demonstrates a pattern for ensuring thread-safe calls to a Windows Forms control. Consulta el System.Windows.Forms.Control.InvokeRequired propiedad, que se compara el control de la creación de Id. de subproceso para el identificador del subproceso que realiza la llamada.It queries the System.Windows.Forms.Control.InvokeRequired property, which compares the control's creating thread ID to the calling thread ID. Si los identificadores de subproceso son iguales, llama directamente al control.If the thread IDs are the same, it calls the control directly. Si los identificadores de subproceso son diferentes, llama a la Control.Invoke método con un delegado a partir del subproceso principal, que realiza la llamada real al control.If the thread IDs are different, it calls the Control.Invoke method with a delegate from the main thread, which makes the actual call to the control.

El SafeCallDelegate habilita la configuración de la TextBox del control Text propiedad.The SafeCallDelegate enables setting the TextBox control's Text property. El WriteTextSafe consultas de método InvokeRequired.The WriteTextSafe method queries InvokeRequired. Si InvokeRequired devuelve true, WriteTextSafe pasa el SafeCallDelegate a la Invoke método para realizar la llamada real al control.If InvokeRequired returns true, WriteTextSafe passes the SafeCallDelegate to the Invoke method to make the actual call to the control. Si InvokeRequired devuelve false, WriteTextSafe establece el TextBox.Text directamente.If InvokeRequired returns false, WriteTextSafe sets the TextBox.Text directly. El Button1_Click controlador de eventos crea el nuevo subproceso y ejecuta el WriteTextSafe método.The Button1_Click event handler creates the new thread and runs the WriteTextSafe method.

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

public class InvokeThreadSafeForm : Form
{
    private delegate void SafeCallDelegate(string text);
    private Button button1;
    private TextBox textBox1;
    private Thread thread2 = null;

    [STAThread]
    static void Main()
    {
        Application.SetCompatibleTextRenderingDefault(false);
        Application.EnableVisualStyles();
        Application.Run(new InvokeThreadSafeForm());
    }
    public InvokeThreadSafeForm()
    {
        button1 = new Button
        {
            Location = new Point(15, 55),
            Size = new Size(240, 20),
            Text = "Set text safely"
        };
        button1.Click += new EventHandler(Button1_Click);
        textBox1 = new TextBox
        {
            Location = new Point(15, 15),
            Size = new Size(240, 20)
        };
        Controls.Add(button1);
        Controls.Add(textBox1);
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        thread2 = new Thread(new ThreadStart(SetText));
        thread2.Start();
        Thread.Sleep(1000);
    }

    private void WriteTextSafe(string text)
    {
        if (textBox1.InvokeRequired)
        {
            var d = new SafeCallDelegate(WriteTextSafe);
            textBox1.Invoke(d, new object[] { text });
        }
        else
        {
            textBox1.Text = text;
        }
    }

    private void SetText()
    {
        WriteTextSafe("This text was set safely.");
    }
}
Imports System.Drawing
Imports System.Threading
Imports System.Windows.Forms

Public Class InvokeThreadSafeForm : Inherits Form

    Public Shared Sub Main()
        Application.SetCompatibleTextRenderingDefault(False)
        Application.EnableVisualStyles()
        Dim frm As New InvokeThreadSafeForm()
        Application.Run(frm)
    End Sub

    Dim WithEvents Button1 As Button
    Dim TextBox1 As TextBox
    Dim Thread2 as Thread = Nothing

    Delegate Sub SafeCallDelegate(text As String)

    Private Sub New()
        Button1 = New Button()
        With Button1
            .Location = New Point(15, 55)
            .Size = New Size(240, 20)
            .Text = "Set text safely"
        End With
        TextBox1 = New TextBox()
        With TextBox1
            .Location = New Point(15, 15)
            .Size = New Size(240, 20)
        End With
        Controls.Add(Button1)
        Controls.Add(TextBox1)
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Thread2 = New Thread(New ThreadStart(AddressOf SetText))
        Thread2.Start()
        Thread.Sleep(1000)
    End Sub

    Private Sub WriteTextSafe(text As String)
        If TextBox1.InvokeRequired Then
            Dim d As New SafeCallDelegate(AddressOf SetText)
            TextBox1.Invoke(d, New Object() {text})
        Else
            TextBox1.Text = text
        End If
    End Sub

    Private Sub SetText()
        WriteTextSafe("This text was set safely.")
    End Sub
End Class

Ejemplo: Usar un controlador de eventos de BackgroundWorkerExample: Use a BackgroundWorker event handler

Una manera fácil es implementar el multithreading con el System.ComponentModel.BackgroundWorker componente, que utiliza un modelo orientado a eventos.An easy way to implement multithreading is with the System.ComponentModel.BackgroundWorker component, which uses an event-driven model. El subproceso en segundo plano se ejecuta el BackgroundWorker.DoWork evento, que no interactúa con el subproceso principal.The background thread runs the BackgroundWorker.DoWork event, which doesn't interact with the main thread. El subproceso principal se ejecuta el BackgroundWorker.ProgressChanged y BackgroundWorker.RunWorkerCompleted controladores de eventos, que pueden llamar a los controles del subproceso principal.The main thread runs the BackgroundWorker.ProgressChanged and BackgroundWorker.RunWorkerCompleted event handlers, which can call the main thread's controls.

Realizar una llamada segura para subprocesos mediante BackgroundWorker, cree un método en el subproceso en segundo plano para realizar el trabajo y enlazarlo a la DoWork eventos.To make a thread-safe call by using BackgroundWorker, create a method in the background thread to do the work, and bind it to the DoWork event. Cree otro método en el subproceso principal para notificar los resultados del trabajo en segundo plano y enlazarlo a la ProgressChanged o RunWorkerCompleted eventos.Create another method in the main thread to report the results of the background work, and bind it to the ProgressChanged or RunWorkerCompleted event. Para iniciar el subproceso en segundo plano, llame a BackgroundWorker.RunWorkerAsync.To start the background thread, call BackgroundWorker.RunWorkerAsync.

El ejemplo se usa el RunWorkerCompleted controlador de eventos para establecer el TextBox del control Text propiedad.The example uses the RunWorkerCompleted event handler to set the TextBox control's Text property. Para obtener un ejemplo que usa el ProgressChanged eventos, consulte BackgroundWorker.For an example using the ProgressChanged event, see BackgroundWorker.

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

public class BackgroundWorkerForm : Form
{
    private BackgroundWorker backgroundWorker1;
    private Button button1;
    private TextBox textBox1;

    [STAThread]
    static void Main()
    {
        Application.SetCompatibleTextRenderingDefault(false);
        Application.EnableVisualStyles();
        Application.Run(new BackgroundWorkerForm());
    }
    public BackgroundWorkerForm()
    {
        backgroundWorker1 = new BackgroundWorker();
        backgroundWorker1.DoWork += new DoWorkEventHandler(BackgroundWorker1_DoWork);
        backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorker1_RunWorkerCompleted);
        button1 = new Button
        {
            Location = new Point(15, 55),
            Size = new Size(240, 20),
            Text = "Set text safely with BackgroundWorker"
        };
        button1.Click += new EventHandler(Button1_Click);
        textBox1 = new TextBox
        {
            Location = new Point(15, 15),
            Size = new Size(240, 20)
        };
        Controls.Add(button1);
        Controls.Add(textBox1);
    }
    private void Button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }

    private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        // Sleep 2 seconds to emulate getting data.
        Thread.Sleep(2000);
        e.Result = "This text was set safely by BackgroundWorker.";
    }

    private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        textBox1.Text = e.Result.ToString();
    }
}
Imports System.ComponentModel
Imports System.Drawing
Imports System.Threading
Imports System.Windows.Forms

Public Class BackgroundWorkerForm : Inherits Form

    Public Shared Sub Main()
        Application.SetCompatibleTextRenderingDefault(False)
        Application.EnableVisualStyles()
        Dim frm As New BackgroundWorkerForm()
        Application.Run(frm)
    End Sub

    Dim WithEvents BackgroundWorker1 As BackgroundWorker
    Dim WithEvents Button1 As Button
    Dim TextBox1 As TextBox

    Private Sub New()
        BackgroundWorker1 = New BackgroundWorker()
        Button1 = New Button()
        With Button1
            .Text = "Set text safely with BackgroundWorker"
            .Location = New Point(15, 55)
            .Size = New Size(240, 20)
        End With
        TextBox1 = New TextBox()
        With TextBox1
            .Location = New Point(15, 15)
            .Size = New Size(240, 20)
        End With
        Controls.Add(Button1)
        Controls.Add(TextBox1)
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        BackgroundWorker1.RunWorkerAsync()
    End Sub

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) _
     Handles BackgroundWorker1.DoWork
        ' Sleep 2 seconds to emulate getting data.
        Thread.Sleep(2000)
        e.Result = "This text was set safely by BackgroundWorker."
    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) _
     Handles BackgroundWorker1.RunWorkerCompleted
        textBox1.Text = e.Result.ToString()
    End Sub
End Class

Vea tambiénSee also