views:

22

answers:

1

Guys,

I have a C# program that executes 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!

+2  A: 

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.

Reed Copsey
So Reed, I could just create a class that has properties for each of my GUI element properties I need, create a new instance of it, fill in the properties, start my thread, have my thread sync lock the class and pull the information as I need it?
icemanind
@icemanind: Yes, you could. If you pull the properties out into a class, you can pass that class in as your work state in QueueUserWorkItem: http://msdn.microsoft.com/en-us/library/4yd16hza.aspx
Reed Copsey
Thank you for the quick replies. This turned out to be one of those "obvious answer in hindsight" haha.. Thanks!
icemanind