dsp_099
dsp_099

Reputation: 6121

How to GRAB a variable from UI thread while in a working thread?

I'm making slow progress on a simple application I'm making: it creates a request, fills out the headers and fetches a webpage for me. I figured out that in order to update the UI (after a button has been pressed) I must use dispatcher like so:

Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new delegate_onearg_s(UpdateStatus), "Sending Request...");

In this case I have an UpdateStatus(string message) which sets my label_Status = message;

So far so good. Now I want it to take input from a textbox first and then turn it into a URL that is used later to create the request, but how do I do that? I've tried this:

string url = Convert.ToString(Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new delegate_string_get(GetInput)));

GetInput() in this case simply does return textBox.Text; That doesn't really work - it returns some generic thing that's related to the dispatcher.

How can I get a variable from a textbox in the UI thread and get it in the working thread with the dispatcher?

Merci beacoup :)

PS. There's a very high probability I don't know what I'm doing. Just keep that in mind when answering.

Upvotes: 3

Views: 896

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292465

You're on the right track, but you need to use Invoke, not BeginInvoke. BeginInvoke executes the delegate asynchronously on the dispatcher thread, but you need to get the result synchronously.

string url = (string)Dispatcher.Invoke(new Func<string>(GetInput));

Upvotes: 1

Eugen
Eugen

Reputation: 2990

before starting the thread, declare a string variable and assign to it the value from textBox then use that variable in your GetInput method.

string myVal = myTextBox.Text;

... use it in your GetInput.

Upvotes: 0

Related Questions