Could someone give me some ideas on the proper “Thread Safe” way to get Label Text from a Form? I am currently getting a CrossThreadingMessaging exception. I know I should be using a delegate, but I am having issues getting this to work correctly. Can someone give me an example? I have a label in my main form that I want to get the text from. I have to make the call from another class. Any guidance here would be much appreciated.
Rob
Here is my scenario:
I have to create an application that will grab the weight from a USB scale and deliver this wait back to a legacy system via a DDE call. The legacy system makes a DDE call to my executable to get the weight via a emulator program. I am trying to mimic the old VB 5 application in a C# application. Believe me there are many other ways I would like to do this, but I was told to do it this way by management. I have captured the weight in the label text, but now I have to get the weight from the label on the main form and return it when the DDE OnRequest method is executed. This is where I am getting the CrossThreading exception. The OnRequest is in a class outside of the main form class of course.
Calling the property getter for a Label’s Text property can be done from a thread without invoking the IllegalOperationException you’d normally get. That’s an implementation detail, the value of the Text property is cached in an internal string. For example:
No exception. But setting the Text property will certainly invoke the hammer. This doesn’t otherwise make it a good idea to use this kind of code. Use threads to perform non-UI related work, give them what they need when you start them. And favor the BackgroundWorker class, it is very handy to give thread-safe progress updates and a thread-safe result.