HttpClient在GetStringAsync方法上冻结

时间:2014-09-27 00:09:39

标签: c# httpclient

我有这个c#MVC代码,它可以与GetAsync和GetPost方法一起使用,但是当使用GetStringAsync时,它会冻结在该行:

version = await client.GetStringAsync("/API/Version");

驱动程序代码:

Task<string>[] tasks = new Task<string>[count];
for (int i = 0; i < count; i++)
{
    tasks[i] = MyHttpClient.GetVersion(port, method);
}
Task.WaitAll(tasks);
string[] results = new string[tasks.Length];
for(int i=0; i<tasks.Length; i++)
{
    Task<string> t = (Task<string>)(tasks[i]);
    results[i] = (string)t.Result;
}

HttpCilent代码:

public static async Task<string> GetVersion(int port, string method)
{
    try
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:" + port);
        string version = null;
        if (method.ToUpper().Equals("GETSTR"))
        {
            version = await client.GetStringAsync("/API/Version");
        }
        else if (method.ToUpper().Equals("GET"))
        {
            HttpResponseMessage res = client.GetAsync("/API/Version").Result;
            version = res.Content.ReadAsStringAsync().Result;
        }
        else if (method.ToUpper().Equals("POST"))
        {
            var content = new FormUrlEncodedContent(new[] 
            {
                new KeyValuePair<string, string>("name", "jax")
            });
            HttpResponseMessage res = client.PostAsync("/API/Version", content).Result;
            version = res.Content.ReadAsStringAsync().Result;
        }
        client.Dispose();
        return version;
    }
    catch (Exception ex)
    {
        return "Error: " + ex.Message;
    }
}
}

任何想法为什么?

1 个答案:

答案 0 :(得分:4)

通常,您不应将async / await.Result.Wait()混在一起。首先修复了GetVersion方法:

public static async Task<string> GetVersion(int port, string method)
{
    try
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:" + port);
            if (method.ToUpper().Equals("GETSTR"))
            {
                return await client.GetStringAsync("/API/Version")
                    .ConfigureAwait(false);
            }
            else if (method.ToUpper().Equals("GET"))
            {
                var res = await client.GetAsync("/API/Version").ConfigureAwait(false);
                return await res.Content.ReadAsStringAsync().ConfigureAwait(false);
            }
            else if (method.ToUpper().Equals("POST"))
            {
                var content = new FormUrlEncodedContent(new[] 
                {
                    new KeyValuePair<string, string>("name", "jax")
                });
                var res = await client.PostAsync("/API/Version", content)
                    .ConfigureAwait(false);
                return await res.Content.ReadAsStringAsync().ConfigureAwait(false);
            }
        }
    }
    catch (Exception ex)
    {
        return "Error: " + ex.Message;
    }
}

我在此处完成的所有操作都将<task>.Result来电替换为await <task>。对于每个awaitawait之后的方法部分将被注册为等待Task的延续 - 如果遇到每个await表达式 - - 而不是在.Result

的情况下阻止线程

现在在您的调用代码中,您需要执行相同的操作:

var tasks = new Task<string>[count];
for (int i = 0; i < count; i++)
{
    tasks[i] = MyHttpClient.GetVersion(port, method);
}
var results = new string[tasks.Length];
for (int i = 0; i < tasks.Length; i++)
{
    results[i] = await tasks[i];
}

或更简单:

var tasks = new Task<string>[count];
for (int i = 0; i < count; i++)
{
    tasks[i] = MyHttpClient.GetVersion(port, method);
}
var results = await Task.WhenAll(tasks);