Trying to update my label from another thread through an interface and a delegate. In debug mode it says the label property is set to the message. But I see nothing at the form itself.
Working in .NET 4.0
A small representation of what I am using:
My Interface:
public interface IMessageListener
{
void SetMessage(string message);
}
the form where I implement it:
public partial class Form1 : Form, IMessageListener
{
...
public void SetMessage(string message)
{
SetControlPropertyValue(ColoLbl, "Text", message);
}
delegate void SetControlValueCallback(Control oControl, string propName, object propValue);
private void SetControlPropertyValue(Control oControl, string propName, object propValue)
{
if (oControl.InvokeRequired)
{
SetControlValueCallback d = new SetControlValueCallback(SetControlPropertyValue);
oControl.Invoke(d, new object[] { oControl, propName, propValue });
}
else
{
Type t = oControl.GetType();
PropertyInfo[] props = t.GetProperties();
foreach (PropertyInfo p in props.Where(p => p.Name.ToUpper() == propName.ToUpper()))
{
p.SetValue(oControl, propValue, null);
}
}
}
}
the class where I try to set the message through the interface. This class is being run from another thread:
public class Controller
{
IMessageListener iMessageListener = new Form1();
...
public void doWork()
{
iMessageListener.SetMessage("Show my message");
}
}
The code compiles all fine, when stepping through with debugging the property of the label does get set, it just doesn’t show on the form itself for some reason.
I suspect it’s either I am missing a line somewhere, or the way the Controller class handles the interface what causes the problem. But i can’t figure out why or what exactly.
The
Textproperty ofColoLblwon’t change in theForm1previously loaded when you calliMessageListener.SetMessage("Show my message");in your code becauseiMessageListenerwas initialized as a newForm1();. It may only change in the new instance created.If you are trying to change
ColoLblvalue inForm1which was initialized before, do not initialize a new instance ofForm1. Instead, initialize anIMessageListenerwhich links to theForm1created previously.Example
Thanks,
I hope you find this helpful 🙂