简体   繁体   中英

Windows Phone - Web client request doesn't get executed

/* 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 WebClient executes its method asynchronously and NotifyComplete() gets executed before the WebClient has 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 method webClient_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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM