Sprache: C#
Wenn aus einem anderen Thread eine Eigenschaft in einem Form-Control geändert werden soll, so muss man mit Callbacks und Invoke arbeiten.
Mit diesem generischen Delegate und der dazugehörigen Funktion, kann man eine Menge Code sparen.
private delegate void SetPropertyValueCallback<ControlType, PropertyType>(ControlType control, string propertyName, PropertyType value) where ControlType : Control;
private void SetPropertyThreadSafe<ControlType, PropertyType>(ControlType control, string propertyName, PropertyType value) where ControlType : Control
{
if (control.InvokeRequired)
{
SetPropertyValueCallback<ControlType, PropertyType> cb = new SetPropertyValueCallback<ControlType, PropertyType>(SetPropertyThreadSafe);
control.Invoke(cb, new object[]{ control, propertyName, value });
}
else
{
System.Reflection.PropertyInfo property = control.GetType().GetProperty(propertyName);
property.SetValue(control, value, null);
}
}
//Anwendung
SetPropertyThreadSafe<ProgressBar, int>(pbState, "Value", (int)syncState.PercentFinished * 100);
SetPropertyThreadSafe<Label, string>(lblState, "Text", syncMessage);
private delegate void SetPropertyValueCallback<ControlType, PropertyType>(ControlType control, string propertyName, PropertyType value) where ControlType : Control;
private void SetPropertyThreadSafe<ControlType, PropertyType>(ControlType control, string propertyName, PropertyType value) where ControlType : Control
{
if (control.InvokeRequired)
{
SetPropertyValueCallback<ControlType, PropertyType> cb = new SetPropertyValueCallback<ControlType, PropertyType>(SetPropertyThreadSafe);
control.Invoke(cb, new object[]{ control, propertyName, value });
}
else
{
System.Reflection.PropertyInfo property = control.GetType().GetProperty(propertyName);
property.SetValue(control, value, null);
}
}
//Anwendung
SetPropertyThreadSafe<ProgressBar, int>(pbState, "Value", (int)syncState.PercentFinished * 100);
SetPropertyThreadSafe<Label, string>(lblState, "Text", syncMessage);
Alte URL:
/snippet/threadsicheres-zuweisen-von-control-eigenschaften/829
Sehr schön, kann ich gebrauchen. Danke!
Sehr gut!!! Danke!
Perfekt. Die Anwendung geht sogar noch einfacher:
SetControlProperty(pbState, „Value“, (int)syncState.PercentFinished);
SetControlProperty(lblState, „Text“, syncState.SyncMessage);