【发布时间】: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
【问题讨论】:
-
如果您不能使您的代码库异步友好,那么请使用 HttpWebRequest 等同步 API 而不是 HttpClient。
标签: c# .net http asynchronous