[英]Windows Phone - Web client request doesn't get executed
/ *在寫這個問題和測試東西的時候,我設法回答了這個問題,我在分享我的發現,這樣對其他可憐的人會有所幫助。 請參閱下面的答案。 * /
我正在嘗試在后台任務中從我的API中獲取JSON數據。 我的后台任務很好並且可以正常運行,但是當我嘗試獲取數據時,什么也沒發生?
這是我使用的代碼:
protected override void OnInvoke(ScheduledTask task)
{
string wurl = @"http://test.com/api/stuff/getdata";
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri(wurl));
NotifyComplete();
}
僅此webClient_DownloadStringCompleted
... webClient_DownloadStringCompleted
永遠不會執行。
這里的關鍵是WebClient
異步執行其方法,並且在WebClient
有機會獲取數據之前先執行NotifyComplete()
。
調用NotifyComplete()
,它會通知OS您已完成執行任務,系統應終止該任務。
解決方案是將NotifyComplete()
移動到異步方法webClient_DownloadStringCompleted
(在本例中為)的末尾,然后... voala!
警告1:您最多有25秒的時間來完成您正在做的事情,否則任務將終止。
警告2:您的后台任務消耗的內存不能超過(在某些手機上)6 MB(在我使用Windows Phone 8測試的仿真器上)需要10 MB的內存! 如果您的后台任務執行了,它將終止。
如果您的應用要消耗更多的內存和時間(最多10分鍾),請考慮使用資源密集型后台任務,請注意,此類任務僅在手機充電時可用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.