0

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?

Bo Milanovich
  • 7,995
  • 9
  • 44
  • 61
  • Are you using WPF or WinForms. If it is WPF, I can share some sample code. – Adam Dec 30 '13 at 14:50
  • Basically, you need to trigger an event on the GUI thread. That's pretty much exactly what `Invoke` does; it sends a message (which refers to a delegate) to the control, and the GUI thread (rather than the current thread) invokes the delegate as part of handling that message. – cHao Dec 30 '13 at 14:58

1 Answers1

0

The workerClass needs to be aware of a concrete instance of testApplication class. Or you could manage this in a higher scope that is aware of both.

sdf
  • 189
  • 3
  • Could you clarify this? How would I do this? – Bo Milanovich Dec 30 '13 at 15:02
  • This would require some code on how the instance of workerClass is created and how the isnstance of testApplication is created? i.e. probably the main method of the program. – sdf Dec 30 '13 at 15:08