将task <string>转换为string

时间:2016-02-17 23:41:57

标签: c# async-await win-universal-app

我想从通用Windows Phone应用程序中的JSON文件解析,但我无法将任务转换为字符串

public MainPage()
    {
        this.InitializeComponent();

        HttpClient httpClient = new HttpClient();
        String responseLine;
        JObject o;
        try
        {
            string responseBodyAsText;

            HttpResponseMessage response = httpClient.GetAsync("http://localhost/list.php").Result;

            //response = await client.PostAsync(url, new FormUrlEncodedContent(values));
            response.EnsureSuccessStatusCode();
            responseBodyAsText = response.Content.ReadAsStringAsync().Result;
           // responseLine = responseBodyAsText;
              string Website = "http://localhost/list.php";
            Task<string> datatask =  httpClient.GetStringAsync(new Uri(string.Format(Website, DateTime.UtcNow.Ticks)));
            string data = await datatask;
            o = JObject.Parse(data);
            Debug.WriteLine("firstname:" + o["id"][0]);
        }
        catch (HttpRequestException hre)
        {
        }

我在这行中有错误

 string data = await datatask;

我该如何解决?

3 个答案:

答案 0 :(得分:2)

您不能在构造函数中使用await。您需要为此创建async方法。

通常我不建议使用async void,但是当你从构造函数中调用它时,它有点合理。

public MainPage()
{
    this.InitializeComponent();
    this.LoadContents();
}

private async void LoadContents()
{
    HttpClient httpClient = new HttpClient();
    String responseLine;
    JObject o;
    try
    {
        string responseBodyAsText;

        HttpResponseMessage response = await httpClient.GetAsync("http://localhost/list.php");

        //response = await client.PostAsync(url, new FormUrlEncodedContent(values));
        response.EnsureSuccessStatusCode();
        responseBodyAsText = await response.Content.ReadAsStringAsync();
       // responseLine = responseBodyAsText;
          string Website = "http://localhost/list.php";
        Task<string> datatask =  httpClient.GetStringAsync(new Uri(string.Format(Website, DateTime.UtcNow.Ticks)));
        string data = await datatask;
        o = JObject.Parse(data);
        Debug.WriteLine("firstname:" + o["id"][0]);
    }
    catch (HttpRequestException hre)
    {
        // You might want to actually handle the exception
        // instead of silently swallowing it.
    }
}

答案 1 :(得分:-1)

尝试一下:

Task<string> post = postPostAsync("Url", data).Result.Content.ReadAsStringAsync();
post.Result.ToString();

答案 2 :(得分:-2)

查看this documentation,您可以使用:Result属性。

例如:

    Task<int> task1 = myAsyncMethod(); //You can also use var instead of Task<int>
    int i = task1.Result;