【发布时间】:2014-07-03 03:43:42
【问题描述】:
我终于得到了一个后台任务,它可以向前台发送 Toast 通知。不幸的是,我遇到了一个问题。我的后台任务需要检查 rss 提要的更新,但是当我运行时
HttpClient hc = new HttpClient();
string result = await hc.GetString("http://url.com");
GetString 方法被触发后没有任何反应,没有返回,它永远不会跳转到下一行。我也试过BackgroundDownload,它也只是像httpclient一样停止,什么时候应该下载?
StorageFolder folder = ApplicationData.Current.TemporaryFolder;
StorageFile file = await folder.CreateFileAsync("feed.txt");
BackgroundDownloader test = new BackgroundDownloader();
DownloadOperation operation = test.CreateDownload(new Uri("https://url.com"), file);
operation.Priority = BackgroundTransferPriority.Default;
await operation.StartAsync();
我到处寻找这个问题的答案,但似乎找不到...那么我如何从网站获取字符串,就像使用 hc.GetString(""); 一样?
这是我的代码:
public async void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
int lastSeenNews = Convert.ToInt32(Settings.GetValue("lastNews"));
int lastNews = 0;
HttpClient hc = new HttpClient();
var rss = await hc.GetStringAsync("https://url.com");
List<RSSItem> items = new List<RSSItem>();
lastNews = items[0].id;
if (lastSeenNews < lastNews)
{
int unreadNotifications = 0;
List<RSSItem> unreadStatuses = items.Where(x => x.id > lastSeenNews).ToList();
unreadNotifications = unreadStatuses.Count;
}
ToastTemplateType toastTemplate = ToastTemplateType.ToastText01;
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
toastTextElements[0].AppendChild(toastXml.CreateTextNode(Settings.GetValue("lastNews")));
ToastNotification toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(toast);
deferral.Complete();
}
【问题讨论】:
-
您是否考虑过
DownloadString可能会抛出异常?将它包裹在 try-catch 中,看看你得到了什么...... -
同样的,从那里永远不会继续,遗憾的是:(
-
@Romasz 这是一个虚拟 URL,不是我在应用中使用的实际 URL:P
-
是的,对 :) 不过,当您尝试使用不同的网址时 - 它是否正确?
-
我的应用程序本身使用相同的方法,工作正常:)
标签: c# windows-phone windows-phone-8.1