Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

await httpClient.SendAsync(httpContent) is not responding though I found no error in code/url its still getting hang. Please suggest/help.

My code as follows:

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;
}

Calling it in another class as follows:

NetUtil u = new NetUtil();
string result = await u.Get_API_Result_String(Register_API, values);
u = null;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
624 views
Welcome To Ask or Share your Answers For Others

1 Answer

I predict that further up your call stack, you are calling Wait or Result on a returned Task. This will cause a deadlock that I explain fully on my blog.

To summarize, await will capture a context and use that to resume the async method; on a UI application this is a UI thread. However, if the UI thread is blocked (in a call to Wait or Result), then that thread is not available to resume the async method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...