/* While writing this question , and testing stuff , i managed to answer the question, I’m sharing my findings so they would be of help to some other poor soul. Please see answer below. */
I’m trying to fetch a JSON data from my API in a background task.
I have the background task nice and running doing it’s thing , but when i try to get the data , nothing happens ?!?
here is the code i use :
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();
}
and that’s all … the webClient_DownloadStringCompleted never gets executed.
The key thing here is that the
WebClientexecutes its method asynchronously andNotifyComplete()gets executed before theWebClienthas the chance to fetch the data.When you call
NotifyComplete(), it notifies the OS that you are done executing your task and the system should terminate it.The solution is to move
NotifyComplete()at the end of the async methodwebClient_DownloadStringCompleted( in this case) and … voala !Warning 1: You have up to 25 seconds to finish whatever you are doing , otherwise the task gets terminated.
Warning 2: Your background task cannot consume more than (on some phones ) 6 MB (on the emulator i tested with windows phone 8) 10 MB of memory! if your background task does , it will be terminated.
It’s good to consider using Resource Intensive background task if your app is going to consume more memory and time ( up to 10 minutes) , note this type of task is only available while the phone is charging!