异步Silverlight 4呼吁C#中的魔兽世界军械库流式XML
-
04-10-2019 - |
题
整个周末我都被困在这个周末,失败了!
请帮助我抓住我的理智!!
您的挑战
对于我的第一个Silverlight应用程序,我认为使用魔兽世界的军械库列出我的行会中的角色会很有趣。这涉及从Silverlight(DUH!)到基于XML的WOW Armory的异步。简单吗?
查看此链接并打开源。您会明白我的意思:http://eu.wowarmory.com/guild-info.xml?r=onar&n=gifted 和才华横溢
以下是获取XML的代码(对ShowGuildies的调用将应对返回的XML-我在本地测试了该XML,并且我知道它有效)。
我根本没有设法获得预期的返回XML。
笔记:
- 如果浏览器能够转换XML,则将提供HTML。我认为它检查了用户
- 我是一个经验丰富的ASP.NET Web开发人员C#,如果您开始谈论Windows表格 / WPF的本机,请轻松
- 由于某种原因,我似乎无法将.NET 4.0设置为.NET 4.0的用户设置 - 似乎不是HTTPWebrequest对象的属性 - 我认为它曾经可用。
- Silverlight 4.0(最初以3.0的形式创建在我将Silverlight安装到4.0之前)
- 使用C#4.0创建
- 请解释一下,就像您与网络开发人员交谈而不是适当的编程大声笑一样!
以下是代码 - 它应该从WOW Armory返回XML。
private void button7_Click(object sender, RoutedEventArgs e)
{
// URL for armoury lookup
string url = @"http://eu.wowarmory.com/guild-info.xml?r=Eonar&n=Gifted and Talented";
// Create the web request
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Set the user agent so we are returned XML and not HTML
//httpWebRequest.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
// Not sure about this dispatcher thing - it's late so i have started to guess.
Dispatcher.BeginInvoke(delegate()
{
// Call asyncronously
IAsyncResult asyncResult = httpWebRequest.BeginGetResponse(ReqCallback, httpWebRequest);
// End the response and use the result
using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult))
{
// Load an XML document from a stream
XDocument x = XDocument.Load(httpWebResponse.GetResponseStream());
// Basic function that will use LINQ to XML to get the list of characters.
ShowGuildies(x);
}
});
}
private void ReqCallback(IAsyncResult asynchronousResult)
{
// Not sure what to do here - maybe update the interface?
}
真的希望有人能帮助我!
谢谢大莫!担。
PS是的,我注意到公会名称的讽刺:)
解决方案
第一的, Dispatcher.BeginInvoke
仅当您在UI线程以外(Silverlight/WPF相关的所有事情发生)时才需要在另一个线程上。在单击事件中,您已经在UI线程中,因此无需调用。
第二, BeginGetResponse
是一个异步操作,因此完成后,它将在另一个线程上调用回调函数,此处 ReqCallback
. 。是在这种方法中,您可以调用 EndGetResponse
. 。此模式适用于您在框架中找到的每个beginx/endx。
但是,由于您在另一个线程中,您需要使用 BeginInvoke
要将方法分配回UI线程。
代码看起来像这样:
private void button7_Click(object sender, RoutedEventArgs e) {
string url = @"http://eu.wowarmory.com/guild-info.xml?r=Eonar&n=Gifted and Talented";
HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create(url);
httpWebRequest.BeginGetResponse(ReqCallback, httpWebRequest);
}
private void ReqCallback(IAsyncResult asyncResult)
{
HttpWebRequest httpWebRequest = (HttpWebRequest) asyncResult.AsyncState;
using (HttpWebResponse httpWebResponse = (HttpWebResponse) httpWebRequest.EndGetResponse(asyncResult))
{
XDocument x = XDocument.Load(httpWebResponse.GetResponseStream());
Dispatcher.BeginInvoke((Action) (() => ShowGuildies(x)));
}
}
请注意,您还可以处理线程中的XML,并仅使用调度程序将公会发送给UI,以免在XML很长的时间分析时冻结UI(不应该这样)。
编辑: 更正了代码。您只需要实施 ShowGuildies
. 。关于互联网连接和延迟,由于操作发生在另一个线程中,因此UI不会冻结。您可能会考虑显示加载动画或其他内容。