What is the simplest way to update a Label from another thread?
I have a Form on thread1, from that I'm starting another thread (thread2). While thread2 is processing some files I would like to update a Label on the Form with the current status of thread2's work.
How can I do that?
Anonymous User
09-Oct-2014which uses LINQ and lambda expressions to allow much cleaner, simpler and safer syntax:
myLabel.SetPropertyThreadSafe(() => myLabel.Text, status);
Not only is the property name now checked at compile time, the property's type is as well, so it's impossible to (for example) assign a string value to a boolean property, and hence cause a runtime exception.
Unfortunately this doesn't stop anyone from doing stupid things such as passing in another Control's property and value, so the following will happily compile:
myLabel.SetPropertyThreadSafe(() => aForm.ShowIcon, false);
Hence I added the runtime checks to ensure that the passed-in property does actually belong to the Control that the method's being called on. Not perfect, but still a lot better than the .NET 2.0 version.