Metric Metric - 2 months ago 14
C# Question

C# generic method for changing a text of a label from an outside thread.

Alright, so this is (hopefully) a pretty easy fix, but I'm trying to create a generic method for allowing outside access of a labels, now the windows documentation does give an example on this for a single case

delegate void SetTextCallback(string text);
...some other code ...
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textLable.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textLable.Text = text;
}
}


However I want to create something a little more generic, where I can pass something along the lines of a pointer to the object, however text labels in windows forms do not allow this. Ideally for this case I'd like something that does something along these line (this won't work in forms obviously, just for explainational purposes)

...code...
private void SetText(string text, Label* lablePointer)
{
if (this.lablePointer.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.lablePointer.Text = text;
}
}


Is there a method for doing this? I've been looking but it doesn't seem to have been answered anywhere.

Answer

You don't need a pointer - you can just do this:

private void SetText(string text, Control control)
{
    if (control.InvokeRequired)
        control.Invoke(new Action(() => control.Text = text));
    else
        control.Text = text;
}

You can use Control instead of Label because the Text property is inherited from Control (Label is derived from Control). This makes it a little more general purpose.

You don't need a pointer because Label (and Control) is a reference type, which means a copy of a reference to the Label object is pushed onto the stack when SetText() is called, which has a similar effect to passing a pointer in C/C++.

(I'm guessing you're a C/C++ programmer who is switching to C#.)