等待httpClient.SendAsync(httpContent)无响应

Pri*_*iti 20 c# windows-phone

await httpClient.SendAsync(httpContent)没有响应,虽然我发现没有错误的代码/网址仍然挂起.请建议/帮助.

我的代码如下:

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;
}
Run Code Online (Sandbox Code Playgroud)

在另一个类中调用它如下:

NetUtil u = new NetUtil();
string result = await u.Get_API_Result_String(Register_API, values);
u = null;
Run Code Online (Sandbox Code Playgroud)

Ste*_*ary 33

我预测你的呼叫堆栈会更远,你正在呼叫WaitResult返回Task.这将导致我在博客上完全解释的死锁.

总而言之,await将捕获上下文并使用它来恢复该async方法; 在UI应用程序上,这是一个UI线程.但是,如果UI线程被阻止(在调用Wait或中Result),则该线程不可用于恢复该async方法.


Gui*_*ini 11

这对我有用:

httpClient.SendAsync(httpContent).ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)

  • 使用这被认为是"不良做法"吗? (3认同)