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

问题描述 投票:1回答:4

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

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

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

当我使用以下代码时:

public MainPage()
{

     this.InitializeComponent();
     Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().SetDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.UseCoreWindow);

     responseBlockTxt.Text = start();
}

public string start()
{
    var response = sendRequest();

    System.Diagnostics.Debug.WriteLine(response);

    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;
      }

}

输出是:

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

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

c# async-await
4个回答
3
投票

一路走Async。调用异步方法时避免阻塞调用。在事件处理程序中允许使用async void,因此更新页面以在load事件上执行调用

阅读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;
    }
}

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


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;
      }

}

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

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

我试过这个。它工作得很好。

© www.soinside.com 2019 - 2024. All rights reserved.