Sna*_*hia 5 c# user-interface windows-phone-7
我是WP7编码的新手.我正在寻找示例代码或指导以下任务:
我在远程服务器上有3个html页面,我想下载每个页面的内容并将其发布到3个不同的全景页面(显示为文本块).
我写了3套webclient来加载html页面; 它可以显示为它所假设的位置.我面临的问题是,在下载时/期间,UI线程是"freez"并且没有响应.
任何人都可以指导我/向我展示示例代码,我可以将线程放到后台,一旦完成,并在UI中显示?
这是我用来下载HTML页面的代码.
private async void GetNewsIndex(string theN)
{
string newsURI = newsURL + theN;
string fileName = theN + "-temp.html";
string folderName = "news";
prgBar01.Visibility = System.Windows.Visibility.Visible;
try
{
Task<string> contentDataDownloaded = new WebClient().DownloadStringTaskAsync(new Uri(newsURI));
string response = await contentDataDownloaded;
WriteTempFile(theN, response.ToString());
string contentData = ProcessDataToXMLNews(fileName, folderName);
WritenewsIndexXMLFile(newsIndexURI, folderName, contentData);
DisplayNewsIndex();
}
catch
{
//
}
}
Run Code Online (Sandbox Code Playgroud)
我根据Sinh Pham的建议修改了上面的代码,它完美地按预期工作.但是,因为我需要运行它的3个瞬间来同时从不同的源下载页面; 代码中断.任何的想法?
您确定 UI 在下载时冻结,而不是在处理数据时冻结吗?从你的代码看来你只是在做
WriteTempFile(theN, response.ToString());
string contentData = ProcessDataToXMLNews(fileName, folderName);
WritenewsIndexXMLFile(newsIndexURI, folderName, contentData);
DisplayNewsIndex();
Run Code Online (Sandbox Code Playgroud)
在 UI 线程上。尝试将它们包装在 BackgroundWorker 中。
编辑:像这样:
Edit2:由于您的 DisplayNewsIndex() 函数会导致 UI 发生变化,因此它必须在 UI 线程上执行。
var bw = new BackgroundWorker();
bw.DoWork += delegate {
WriteTempFile(theN, response.ToString());
string contentData = ProcessDataToXMLNews(fileName, folderName);
WritenewsIndexXMLFile(newsIndexURI, folderName, contentData);
Deployment.Current.Dispatcher.BeginInvoke(() => {
DisplayNewsIndex();
});
};
bw.RunWorkerAsync();
Run Code Online (Sandbox Code Playgroud)