【问题标题】:convert task<string> to string [duplicate]将任务 <string> 转换为字符串 [重复]
【发布时间】:2020-12-16 21:53:11
【问题描述】:

我想从通用 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;

我该如何解决?

【问题讨论】:

  • string data = datatask.Result; 可以工作吗?

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


【解决方案1】:

你不能在构造函数中使用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.
    }
}

【讨论】:

  • 我尝试了这段代码,但我得到了这个错误 Newtonsoft.Json.dll 中发生了“Newtonsoft.Json.JsonReaderException”类型的异常,但未在用户代码中处理
  • @AlaEddineHelmiHaouala,在调试器下检查您的data 字符串。您可能正在处理格式错误的 JSON(或非 JSON 内容)。
  • 感谢您的回答,但是当我调用异步方法来显示我的产品列表时,它没有显示在模拟器中,但显示在控制台中。她有什么问题?
  • 最好的做法是使用 Task 作为返回类型而不是 Void。我们不应该使用 Async 方法中的 void。
【解决方案2】:

查看this documentation,您可以使用:Result 属性来获得它。

例如:

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

【讨论】:

  • 在类构造函数中放置诸如Task.Result之类的阻塞方法并不是一个好主意。
  • @Peregrine 为什么不呢?
【解决方案3】:

试试这个:

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

【讨论】:

  • 欢迎来到 SO!请阅读游览tourHow to Answer 一个问题。这个问题是 4 年前提出的。
  • @GoodJuJu 回答 4 岁或以上的问题有问题吗?我之所以这么问,是因为我自己已经回答了很多 8 到 9 岁的问题,而且我从来没有收到反馈说这是不合适的事情。
猜你喜欢
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
  • 2011-09-08
  • 2012-10-04
  • 1970-01-01
  • 2020-11-22
  • 1970-01-01
  • 2014-01-19
相关资源
最近更新 更多