我正在尝试使用GetStringAsync方法访问我的网址,但是通话挂起并且永远不会结束。当我在浏览器中检查它时它工作得很完美但不知何故在我的代码中它永远不会结束。我的代码:
public bool Login(string url,string userName, string password)
{
try
{
Task<LoginResponse> response = GetLoginData(url, userName, password);
if(response.Result.UserInfo.UserId > 0){
IsAuthenticated = true;
}
return IsAuthenticated;
}
catch (ArgumentException argex)
{
ErrorMessage = argex.Message;
IsAuthenticated = false;
return IsAuthenticated;
}
}
public async Task<LoginResponse> GetLoginData(string url, string userName, string password)
{
try{
var param = new AuthenticationParam();
param.UserName = userName;
param.Password = password;
var response = await LoginValidate(url, param);
response = response.Replace("\"", string.Empty);
response = response.Replace("\\", "\"");
LoginResponse list = JsonConvert.DeserializeObject<LoginResponse>(
response, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
return list;
}
catch(Exception e){
System.Diagnostics.Debug.WriteLine(e);
return new LoginResponse();
}
}
private static async Task<string> LoginValidate(string url, AuthenticationParam param){
try
{
string result = "";
using (var client = new HttpClient())
{
var json_data = string.Empty;
json_data = JsonConvert.SerializeObject(param);
var byteArray = Encoding.UTF8.GetBytes(json_data);
var base64 = Convert.ToBase64String(byteArray);
url = $"{url}{base64}";
result = await client.GetStringAsync(url);
return result;
}
}
catch (Exception ex)
{
return "Error: " + ex.Message;
}
}
它挂起在行 result = await client.GetStringAsync(url);
答案 0 :(得分:5)
if(response.Result.UserInfo.UserId > 0){
- &gt; .Result是一个阻止调用,可能会导致死锁。使用await一直到调用链。
public async Task<bool> Login(string url,string userName, string password)
{
try
{
var response = await GetLoginData(url, userName, password);
if(response.UserInfo.UserId > 0){
IsAuthenticated = true;
}
return IsAuthenticated;
}
catch (ArgumentException argex)
{
ErrorMessage = argex.Message;
IsAuthenticated = false;
return IsAuthenticated;
}
}
在调用堆栈中使用var success = await Login(...);
请阅读this优秀博客文章,了解如何创建此死锁。