简体   繁体   English

Windows Phone-Web客户端请求未执行

[英]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. 我正在尝试在后台任务中从我的API中获取JSON数据。 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. 仅此webClient_DownloadStringCompleted ... webClient_DownloadStringCompleted永远不会执行。

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. 这里的关键是WebClient 异步执行其方法,并且在WebClient有机会获取数据之前先执行NotifyComplete()

When you call NotifyComplete() , it notifies the OS that you are done executing your task and the system should terminate it. 调用NotifyComplete() ,它会通知OS您已完成执行任务,系统应终止该任务。

The solution is to move NotifyComplete() at the end of the async method webClient_DownloadStringCompleted ( in this case) and ... voala ! 解决方案是将NotifyComplete()移动到异步方法webClient_DownloadStringCompleted (在本例中为)的末尾,然后... voala!

Warning 1: You have up to 25 seconds to finish whatever you are doing , otherwise the task gets terminated. 警告1:您最多有25秒的时间来完成您正在做的事情,否则任务将终止。

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! 警告2:您的后台任务消耗的内存不能超过(在某些手机上)6 MB(在我使用Windows Phone 8测试的仿真器上)需要10 MB的内存! 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! 如果您的应用要消耗更多的内存和时间(最多10分钟),请考虑使用资源密集型后台任务,请注意,此类任务仅在手机充电时可用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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