【问题标题】:C# stops working when performing async post request执行异步发布请求时 C# 停止工作
【发布时间】:2018-05-16 23:43:45
【问题描述】:

我正在开发一个移动应用程序,问题是当我使用 Net.Http 执行异步请求 ( PostAsync ) 时,我的程序停止运行。

这是我的请求类,我使用 Net.Http 执行请求。

...

namespace BSoft.Requests
{
   public class Requests
    {
      public Requests(){}

       public static string HostName =  "https://dev5.360businesssoft.com/";

    private static readonly HttpClient httpClient = new HttpClient();

    public static async Task<string> PerformPostRequest(Dictionary<string, string> values, string path)
    {
        string url = HostName + path;
        FormUrlEncodedContent content = new FormUrlEncodedContent(values);
        HttpResponseMessage response = await httpClient.PostAsync(url, content);
        string responseString = await response.Content.ReadAsStringAsync();
        return responseString;
    }

}
}

这是我的登录类,我在其中调用请求并将结果显示为字符串。

... 

namespace BSoft.Login
{
public class Login
{
    public Login()
    {
    }      

    public static void PerformLogin(string username, string password, bool remember)
    {
        var values = new Dictionary<string, string>();
        values.Add("User", username);
        values.Add("Password", password);

        var ReturnedObj = Requests.Requests.PerformPostRequest(values, "test.php").Result;
        System.Diagnostics.Debug.WriteLine(ReturnedObj);
    }
}
}

This is a screenshot of the app, you can notice that the button is freezed

【问题讨论】:

标签: c# .net http asynchronous


【解决方案1】:

Result 的调用阻塞了gui 线程。相反,await 结果:

var ReturnedObj = await Requests.Requests.PerformPostRequest(values, "test.php");
System.Diagnostics.Debug.WriteLine(ReturnedObj);

您对Result 的调用将阻塞gui 线程,直到PerformPostRequest 完成,所以在这里使用async 功能并没有多大意义。如果您真的不希望代码异步执行,那么您不妨删除对 async 方法的调用并使调用同步。

【讨论】:

  • 最好警告签名应更改为async Task
  • Jorge Aguiar 已经回答了这个问题,但是有没有办法在我的 PerformLogin 函数中不使用异步来修复它?
  • @DariusBuhai - 由于您的代码实际上是异步运行的,因此您始终可以只调用同步方法并让您的 gui 线程阻止调用正在发生。这基本上就是你所拥有的。
【解决方案2】:

试试

string returnedString = await Requests.Requests.PerformPostRequest(values, "test.php");

【讨论】:

  • 这可以工作,但我不想在我的 PerformLogin 函数中使用异步
  • 除了在每个函数中使用异步之外,还有其他方法可以做到这一点吗?
  • 并非如此。 async/await 通常是“一路乌龟”。
猜你喜欢
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
相关资源
最近更新 更多