这个异步链的实现有什么问题?

时间:2018-04-23 03:15:46

标签: c# .net asynchronous async-await

我在控制台应用中有以下代码。调用LookUpUser方法并调用PostAsJsonAsync,但响应检查中的断点之后不会被命中。我在这个实现中做错了什么?

static void Main(string[] args)
{
    TestUseCase().GetAwaiter().GetResult();
}

private static async Task TestUseCase()
{
    await GetUserGuids();
}

private static async Task GetUserGuids()
{
    var userGuids = new List<Guid>();
    userGuids.Add(Guid.Parse("7b5cf09c-196c-4e0b-a0e2-0683e4f11213"));
    userGuids.Add(Guid.Parse("3a636154-b7fc-4d96-9cd1-d806119ff79f"));
    userGuids.ForEach(async x => await LookUpUser(x));
}

private static async Task LookUpUser(Guid adUserGuid)
{
    var client = new HttpClientManager().GetHttpClient();
    var response = await client.PostAsJsonAsync("api/v1/users/search", new { ADUserGuid = adUserGuid });
    if (response.IsSuccessStatusCode)
    {
        var groups = await response.Content.ReadAsAsync<List<User>>();
    }
    else //not 200
    {
        var message = await response.Content.ReadAsStringAsync();
    }
}

2 个答案:

答案 0 :(得分:4)

 userGuids.ForEach(async x => await LookUpUser(x));

ForEach中的代表基本上是async void(火与忘记)

考虑选择Task的集合,然后使用Task.WhenAll

private static async Task GetUserGuids() {
    var userGuids = new List<Guid>();
    userGuids.Add(Guid.Parse("7b5cf09c-196c-4e0b-a0e2-0683e4f11213"));
    userGuids.Add(Guid.Parse("3a636154-b7fc-4d96-9cd1-d806119ff79f"));
    var tasks = userGuids.Select(x => LookUpUser(x)).ToArray();
    await Task.WhenAll(tasks);
}

同样假设HttpClientManager.GetHttpClient()返回HttpClient,则无需创建多个实例。在静态客户端上应该

static HttpClient client = new HttpClientManager().GetHttpClient();
private static async Task LookUpUser(Guid adUserGuid) {
    var response = await client.PostAsJsonAsync("api/v1/users/search", new { ADUserGuid = adUserGuid });
    if (response.IsSuccessStatusCode) {
        var groups = await response.Content.ReadAsAsync<List<User>>();
    } else  {
        //not 200
        var message = await response.Content.ReadAsStringAsync();
    }
}

答案 1 :(得分:2)

我通过将ForEach更改为:

来实现它
foreach (var guid in userGuids)
{
    await LookUpUserInSecurityApi(guid);
}