【问题标题】:WP8 Fast App Resume with Asynchronous methods使用异步方法的 WP8 快速应用程序恢复
【发布时间】:2014-03-13 11:00:07
【问题描述】:

在我的 windows phone 8 应用程序中,我使用异步方法从服务器检索数据。

在实现Fast App Resume 功能后,我又遇到了另一个问题。从服务器检索数据的异步方法在恢复时会抛出 System.Net.WebException 类型的异常。

重现问题的步骤是当应用程序通过异步方法加载数据时,您只需点击开始按钮。

例如,我有一个加载用户通知的页面。我调用了async void GetNotifications() 方法,该方法进一步调用下面的方法来检索响应字符串。

    public async Task<string> Get(string URL)
    {
        var request = WebRequest.Create(new Uri(URL)) as HttpWebRequest;

        if (APIHelper.APIHandshake != null)
            request.Headers["Cookie"] = "ii=" + APIHelper.APIHandshake.Sid + ";";

        return await httpRequest(request);
    } 

httprequest方法的实现如下。

    private async Task<string> httpRequest(HttpWebRequest request)
    {
        string received;

        using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory
            .FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
        {
            using (var responseStream = response.GetResponseStream())
            {
                using (var sr = new StreamReader(responseStream))
                {
                    //cookieJar = request.CookieContainer;
                    //responseCookies = response.Cookies;
                    received = await sr.ReadToEndAsync();
                }
            }
        }

        return received.Replace("[{}]", "[]")
                .Replace("[{},{}]", "[]")
                .Replace("\"subcat_id\":\"\"", "\"subcat_id\":\"0\"");
    }

用户只需单击打开通知页面的菜单,然后立即按下手机的开始按钮即可停用应用程序。当用户从开始菜单单击应用程序磁贴时,将引发异常。

有什么解决办法吗?停用空闲模式检测会起作用吗?

【问题讨论】:

    标签: c# asynchronous windows-phone-8 fast-app-switching


    【解决方案1】:

    这可能不是最好的解决方案,但可以通过在 app.xaml.cs 页面的 InitalizePhoneApplication() 方法中添加这行代码来不取消异步请求。

    PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
    

    阅读更多关于这个属性here
    测试一下,它应该可以解决问题,但我并没有假装这是最好的做法......

    【讨论】:

    • 不,它没有用,我认为你正在采取另一种方式
    猜你喜欢
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    相关资源
    最近更新 更多