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");
});
Alte URL:
/snippet/threadsicherer-codeaufruf-im-control-kontext-invoking/1177
Sehr praktisch.
Kennst du auch SynchronizationContext und/oder AsyncOperation?
Also die Async-Operationen mit IAsyncResult kenne ich. Mit dem SynchronizationContext habe ich bisher noch nicht gearbeitet.
[quote]Async-Operationen mit IAsyncResult[/quote] Nein, ich meine die AsyncOperation aus System.ComponentModel. Siehe hierzu: http://www.codeproject.com/KB/cpp/SyncContextTutorial.aspx
Einen dreiteiligen Artikel zum SynchronizationContext gibt es hier:
http://www.codeproject.com/KB/threads/SynchronizationContext.aspx
http://www.codeproject.com/KB/threads/SynchronizationContext2.aspx
http://www.codeproject.com/KB/threads/SynchronizationContext3.aspx
Er behandelt das Thema ausführlich und beinhaltet praktische Beispiele.
Ah, super, vielen Dank für die vielen Infos.
Bei Gelegenheit werde ich mir das mal alles anschauen.
Aus aktullem Anlass habe ich mir erlaubt, eine kleine Beispielanwendung für Anfänger zu basteln.
http://dotnet-forum.de/forums/p/1772/6435.aspx#6435