执行异步发布请求时,C#停止工作

时间:2018-05-16 15:34:05

标签: c# .net http asynchronous

我正在开发移动应用,问题是当我使用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

2 个答案:

答案 0 :(得分:4)

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

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

您对Result的调用将阻止gui线程直到PerformPostRequest完成,因此使用async功能并不是很重要。如果你真的不希望代码异步执行,那么你也可以删除对异步方法的调用并使调用同步。

答案 1 :(得分:1)

尝试

string returnedString = await Requests.Requests.PerformPostRequest(values, "test.php");
相关问题