C# 等待httpClient.SendAsync(httpContent)没有响应

C# 等待httpClient.SendAsync(httpContent)没有响应,c#,windows-phone,C#,Windows Phone,等待httpClient.SendAsync(httpContent)没有响应,尽管我在代码/url中没有发现错误,但它仍然挂起。请建议/帮助 我的代码如下: public async Task<string> Get_API_Result_String(string url, List<KeyValuePair<string, string>> parameters) { string res = ""; try {

等待httpClient.SendAsync(httpContent)
没有响应,尽管我在代码/url中没有发现错误,但它仍然挂起。请建议/帮助

我的代码如下:

public async Task<string> Get_API_Result_String(string url, List<KeyValuePair<string, string>> parameters)
{
    string res = "";

    try
    {
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

        //Prepare url
        Uri mainurl = new Uri(settings[FSAPARAM.UserSettingsParam.SERVERNAME].ToString());
        Uri requesturl = new Uri(mainurl, url);

        var httpClient = new HttpClient();
        var httpContent = new HttpRequestMessage(HttpMethod.Post, requesturl);
        // httpContent.Headers.ExpectContinue = false;

        httpContent.Content = new FormUrlEncodedContent(parameters);

        HttpResponseMessage response = await httpClient.SendAsync(httpContent);

        var result = await response.Content.ReadAsStringAsync();
        res = result.ToString();

        response.Dispose();
        httpClient.Dispose();
        httpContent.Dispose();
    }
    catch (Exception ex)
    {
        Logger l = new Logger();
        l.LogInfo("Get_API_Result_String: "+ url + ex.Message.ToString());
        ex = null;
        l = null;
    }

    return res;
}
NetUtil u = new NetUtil();
string result = await u.Get_API_Result_String(Register_API, values);
u = null;

我预测,在调用堆栈的更上层,您正在对返回的任务调用
Wait
Result
。我在我的博客上详细解释了这一点

总之,
await
将捕获一个上下文,并使用该上下文恢复
async
方法;在UI应用程序上,这是一个UI线程。但是,如果UI线程被阻止(在调用
Wait
Result
时),则该线程无法恢复
async
方法。

这对我来说很有效:

httpClient.SendAsync(httpContent).ConfigureAwait(false);

我刚刚删除了
wait
,并按如下方式使用,效果良好:

var result = httpClient.SendAsync(httpContent).Result;
但这不是一个好的做法。 作为 如上所述,我们不应该混合使用同步和异步调用。
我将调用方法更改为async,问题得到了解决。

这对我来说没问题

  var response = httpClient.SendAsync(request);
  var responseResult = response.Result;

  if (responseResult.IsSuccessStatusCode)
  {
         var result = responseResult.Content.ReadAsStringAsync().Result;
         return result;
  }

在返回压缩的gzip数据时遇到了这个错误。这是一种非常罕见的情况,因为99%的时间使用不同的输入数据,一切都很好。必须切换到HttpWebRequest。

是的,我检查过了。我用wait调用了每一个上层方法。我试图在testApp中放置完全相同的场景,在那里它工作得很好。纽约当前的项目有很多代码,所以我仔细地到处跟踪以找到死锁。ThanksI在应用程序启动时使用了async,因为我必须在应用程序启动时调用async方法,我认为这会造成问题。你能帮个忙吗?这种使用被认为是“不好的做法”吗?添加了IsSuccessStatusCode检查