Retrieving properties from a GUI object in a thread
I have a C# program that execu开发者_运维知识库tes a thread. Inside this thread, I have the following code:
string strDropDownValue = (string)ddlVersion.SelectedItem;
I am trying to retrieve the selected value from the drop down list. This line works, obviously, in a single threaded application. Because I'm doing this from a thread though, I get a cross thread exception at runtime. I know that if I want to change a value of a GUI object from a thread, I need to use InvokeRequired() and Invoke(). However, what do I do if I just want to read a property value? Do I still need Invoke()? I tried looking for a solution to this but couldn't find an example. All the examples I found show how to set a property, but not how to read it. Any help would be appreciated!
Yes, you would still need to invoke, and pull the string out of the control on the UI thread. You can then pass it back into your other thread via some synchronized variable, or something similar.
That being said, typically, you would pull the information out of the control before you start your background thread, and just pass it into the background thread. That's why, I suspect, you don't find many pieces of code showing how to accomplish this.
精彩评论