[英]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:
我发现,为了更新UI(按下按钮后),我必须使用调度程序,如下所示:
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; 在这种情况下,我有一个UpdateStatus(字符串消息),它设置我的label_Status =消息;
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?
现在我希望它首先从文本框中获取输入,然后将其转换为稍后用于创建请求的URL,但我该如何做? 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; 在这种情况下,GetInput()只返回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? 如何从UI线程中的文本框中获取变量并将其与调度程序一起放入工作线程中?
Merci beacoup :) Merci beacoup :)
PS. PS。 There's a very high probability I don't know what I'm doing.
我很不可能知道自己在做什么。 Just keep that in mind when answering.
请回答时牢记这一点。
You're on the right track, but you need to use Invoke
, not BeginInvoke
. 你是在正确的轨道上,但你需要使用
Invoke
,而不是BeginInvoke
。 BeginInvoke
executes the delegate asynchronously on the dispatcher thread, but you need to get the result synchronously. BeginInvoke
在调度程序线程上异步执行委托,但您需要同步获取结果。
string url = (string)Dispatcher.Invoke(new Func<string>(GetInput));
before starting the thread, declare a string variable and assign to it the value from textBox then use that variable in your GetInput method. 在启动线程之前,声明一个字符串变量并从textBox中为其赋值,然后在GetInput方法中使用该变量。
string myVal = myTextBox.Text;
... use it in your GetInput. ...在GetInput中使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.