Feedback

Threadsicherer Codeaufruf im Control-Kontext (Invoking)

Sprache: C#

Diese Extension-Methode ermöglicht das Ausführen von Anweisungen im Kontext eines Controls mit Hilfe von InvokeRequired. Hierdurch können Eigenschaften threadsicher zugewiesen, bzw. Methoden ausgeführt werden.
public static void ExecuteThreadSafe(this Control control, Action action)
{
    if (control.InvokeRequired)
    {
        control.Invoke(action);
    }
    else
    {
        action.Invoke();
    }
}


//Beispiel:
comboBox.ExecuteThreadSafe(() => comboBox.Enabled = true);

comboBox.ExecuteThreadSafe(() =>
{
    comboBox.Enabled = true;
    comboBox.Items.Add("Threadsicheres");
    comboBox.Items.Add("hinzufügen");
    comboBox.Items.Add("von");
    comboBox.Items.Add("Items");
});
public static void ExecuteThreadSafe(this Control control, Action action)
{
    if (control.InvokeRequired)
    {
        control.Invoke(action);
    }
    else
    {
        action.Invoke();
    }
}


//Beispiel:
comboBox.ExecuteThreadSafe(() => comboBox.Enabled = true);

comboBox.ExecuteThreadSafe(() =>
{
    comboBox.Enabled = true;
    comboBox.Items.Add("Threadsicheres");
    comboBox.Items.Add("hinzufügen");
    comboBox.Items.Add("von");
    comboBox.Items.Add("Items");
});

6 Kommentare

  1. Also die Async-Operationen mit IAsyncResult kenne ich. Mit dem SynchronizationContext habe ich bisher noch nicht gearbeitet.