暂停文本框更新,直到http调用WP7
本文关键字:http 调用 WP7 直到 文本 更新 暂停 | 更新日期: 2023-09-27 18:17:58
我有一个类request
,它有一个方法call
,它发出一个http请求
在我的主类中,当用户按下一个按钮时,类req
的一个实例被创建,方法call
使http请求被调用。
我想有一种特定的方式知道调用何时完成,以便我可以用结果更新我的文本块
我试图把它放在按钮点击事件处理程序方法中:
req.call(textBox1.Text);
Dispatcher.BeginInvoke(() =>
{
//req is the class instance, outputMessage is the string holds
//the result of the http request
//resultTextBlock is the one I wanna update with the result
while (req.outputMessage == "none") ;
resultTextBlock.Text = req.outputMessage;
});
中的按钮点击事件处理程序,但随后应用程序进入无限循环,永远不会完成,HTTP请求需要几分之一秒,如果这是重要的
我希望能够更新resultTextBlock
每当结果被抓取
您希望请求完成后得到一个回调。这是由WebClient
:
using (WebClient wc = new WebClient())
{
wc.DownloadStringAsync(new Uri("http://stackoverflow.com"), null);
wc.DownloadStringCompleted += (s, e) =>
{
string outputMessage = e.Result;
Dispatcher.BeginInvoke(() =>
{
resultTextBlock.Text = outputMessage;
});
};
}
编辑:你可以传递一个委托给你的req
类,你传递的结果字符串(也注意命名准则,应该全部大写),所以改变方法签名如下:
public void Call(string url, Action<string> notifyCompletion)
{
//once completed:
notifyCompletion(result);
}
并将调用代码更改为:
Req myRequest = new Req();
myRequest.Call(textBox1.Text, s =>
{
Dispatcher.BeginInvoke(() =>
{
resultTextBlock.Text = outputMessage;
});
});