0

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.

user1599271
  • 69
  • 1
  • 8

1 Answers1

0

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:

    private void button1_Click(object sender, EventArgs e) {
        var t = new Thread(() => Console.WriteLine(label1.Text));
        t.Start();
    }

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Thanks for the info. Please take a look at my updated scenario, and any comments or suggestions would be great. – user1599271 Aug 22 '12 at 17:48