简体   繁体   中英

what's wrong with the implementation of this async chain?

I have the code below in a console app. The LookUpUser method gets called and PostAsJsonAsync gets called but breakpoints in the response checking don't get hit afterwards. What am I doing incorrectly in this implementation?

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();
    }
}
 userGuids.ForEach(async x => await LookUpUser(x));

The delegate in the ForEach is basically a async void (fire and forget)

Consider selecting a collection of Task and then use 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);
}

Also assuming HttpClientManager.GetHttpClient() returns a HttpClient there is no need to create multiple instances. on static client should do

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

I got it to work by changing the ForEach to:

foreach (var guid in userGuids)
{
    await LookUpUserInSecurityApi(guid);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM