I am relatively new to C# and I have been having some difficulties figuring out how exactly to update the text property of a Label in C#.
To clarify, I have a Label that obviously lives in the main thread and that can be found in a class named myClass
.
The worker thread method, on the other hand, lives in a class named workerClass
. Both of the classes are obviously in the same namespace. Here's the sample code:
GUI class:
namespace testApplication
{
public partial class testApplication : Form
{
///Code here
public void changeLabelText(String text)
{
label1.Text = text;
}
}
}
There's of course a method that starts a thread and all that, and that part works fine.
The worker class code looks very similar to the one above (does not inherit from Form class naturally). Everything works fine, except I can't figure out how to update the GUI from that worker thread/class. I went over a few MSDN tutorials but did not find them very useful, mostly because in their cases all of their methods live in one class.
I've tried creating a new instance of the testApplication class (the GUI shown above) in the worker thread itself (though that didn't make sense to begin with), and then call the changeLabelText
method (which at one point contained the .Invoke
method as well), but that didn't work (though an Exception was not raised).
So, to make it simple: how do I update a GUI element from a different thread that lives in a different class?