所以我有一个类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
。
答案 0 :(得分:1)
完成后,您需要来自请求的回调。这得到了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;
});
});