Feedback

Threadsicheres Zuweisen von Control-Eigenschaften

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);

3 Kommentare

  1. Perfekt. Die Anwendung geht sogar noch einfacher:
    SetControlProperty(pbState, „Value“, (int)syncState.PercentFinished);
    SetControlProperty(lblState, „Text“, syncState.SyncMessage);