UploadStringAsync在Windows Phone 8中不起作用

时间:2014-08-29 14:58:28

标签: c# windows-phone-8 windows-phone async-await

我是C#的新手,我想在Windows Phone应用程序中为我的RESTlike API创建库。

我的api结构有点

http://mysiteurl/api/method_name.json

所以我想用(method_name,params)调用api并返回指定的类。

当我在Windows Phone 8.1程序上启动此代码冻结时,没有任何反应。我也可以在服务器端看到任何内容(任何电话)

API.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Diagnostics;
using System.Threading.Tasks;
using Newtonsoft.Json;
using SampleProg.Model;

namespace SampleProg.Lib
{
    public class Api
    {
        public async Task<VersionClass> versionInfo()
        {
            Debug.WriteLine("versionInfo()");
            var result = await this.Post<VersionClass>("version", "{}", null);
            Debug.WriteLine(result);
            return result;
        }

        public async Task<TReturnType> Post<TReturnType>(string methodName, string data, Dictionary<string, string> headers)
        {
            var webClient = new WebClient();

            webClient.Headers["Content-Type"] = "application/json";
            webClient.Encoding = Encoding.UTF8;

            var uri = new Uri(String.Format("http://mysiteurl/api/{0}.json", methodName));

            if (headers != null)
            {
                foreach (var key in headers.Keys)
                {
                    webClient.Headers[key] = headers[key];
                }
            }

            return await Post<TReturnType>(webClient, uri, data);
        }

        private async Task<TReturnType> Post<TReturnType>(WebClient webClient, Uri uri, string jsonData)
        {
            TReturnType returnObject = default(TReturnType);

            var taskCompletionSource = new TaskCompletionSource<TReturnType>();

            webClient.UploadStringCompleted += (s, e) =>
            {
                var result = e.Result;

                try
                {
                    Debug.WriteLine(result);
                    returnObject = JsonConvert.DeserializeObject<TReturnType>(result);

                    taskCompletionSource.SetResult(returnObject);
                }
                catch (Exception ex)
                {
                    var newEx = new Exception(
                      string.Format("Failed to deserialize server response: {0}", result), ex);
                    taskCompletionSource.SetException(newEx);
                }
            };

            webClient.UploadStringAsync(uri, "POST", jsonData);

            return await taskCompletionSource.Task;
        }

    }
}

App.xaml.cs(我从公共App(){}中调用它:

var api = new Api();
var apiTask = api.versionInfo();
VersionClass version = (VersionClass)apiTask.Result;
Debug.WriteLine(version.num);

VersionClass.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace SampleProg.Model
{
    public class VersionClass
    {
        [JsonProperty("version")]
        public int num { get; set; }

    }
}
你可以告诉我出了什么问题吗?我使用此代码(在底部)http://sandor68.rssing.com/chan-11557297/all_p1.html作为基础

1 个答案:

答案 0 :(得分:1)

此:

VersionClass version = (VersionClass) apiTask.Result;

您的应用程序陷入僵局。

SynchronizationContext试图在内部方法UI thread之后将控制权归还给await

发生了什么事。

您应该await始终 Task

VersionClass version = (VersionClass) await apiTask;

此外,请注意,已经通过WebClient.UploadStringTaskAsync

为您提供了返回UploadStringAsync的{​​{1}}包裹OOTB

修改

如果您选择继续使用Task版本,则不应在返回的Postawait,您应该让用户执行此操作,并从{{取消注册处理程序1}}:

Task