将异步任务响应转换为字符串

时间:2017-01-15 13:35:30

标签: c# async-await

首先,我想说,我对C#很新。

我试图创建一个POST请求,将一些数据发送到另一台服务器上的某个PHP文件。

现在,在发送请求之后,我希望看到响应,因为我从服务器发回JSON字符串作为成功消息。

当我使用以下代码时:

"colnames<-"(paste0("column_set_", colnames(.)))

输出结果为:

  

System.Threading.Tasks.Task`1 [System.String]

那么,我怎样才能看到这一切的结果?

4 个答案:

答案 0 :(得分:3)

一直走Async。调用异步方法时避免阻塞调用。事件处理程序中允许async void,因此更新页面以执行对加载事件的调用

阅读Async/Await - Best Practices in Asynchronous Programming

然后相应地更新您的代码

public MainPage() {    
    this.InitializeComponent();
    Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().SetDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.UseCoreWindow);
    this.Loaded += OnLoaded;     
}

public async void OnLoaded(object sender, RoutedEventArgs e) {
    responseBlockTxt.Text = await start();
}

public async Task<string> start() {
    var response = await sendRequest();

    System.Diagnostics.Debug.WriteLine(response);

    return response;
}

private static HttpClient client = new HttpClient();

public async Task<string> sendRequest() {
    var values = new Dictionary<string, string> {
        { "vote", "true" },
        { "slug", "the-slug" }
    };

    var content = new FormUrlEncodedContent(values);
    using(var response = await client.PostAsync("URL/api.php", content)) {
        var responseString = await response.Content.ReadAsStringAsync();
        return responseString;
    }
}

答案 1 :(得分:0)

问题出在start方法中,SendRequest方法会返回Task<string>,这就是您在response变量上获得的内容。由于您尝试同步运行async方法,因此必须执行一些额外的操作,请尝试以下操作:

public string start()
{
    var response = sendRequest().ConfigureAwait(true)
                                .GetAwaiter()
                                .GetResult();

    System.Diagnostics.Debug.WriteLine(response);

    return "";
}

在你等待的Task<string>中获得实际结果。如果您想了解更多相关信息,请查看this question

答案 2 :(得分:0)

我猜猜

public string start()
{
    var response = sendRequest();
    Task<String> t = sendRequest();
    System.Diagnostics.Debug.WriteLine(t.Result);

    return "";
}

public async Task<string> sendRequest()
{
     using (var client = new HttpClient())
     {
          var values = new Dictionary<string, string>
          {
               { "vote", "true" },
               { "slug", "the-slug" }
          };

          var content = new FormUrlEncodedContent(values);

          var response = await client.PostAsync("URL/api.php", content);

          var responseString = await response.Content.ReadAsStringAsync();

          return responseString;
      }

}

答案 3 :(得分:0)

public string start()
  {
    var response = sendRequest().ConfigureAwait(true)
                                .GetAwaiter()
                                .GetResult();

    System.Diagnostics.Debug.WriteLine(response);
    return "";
   }

我已经尝试过了。运行良好。