C#C
C#14mo ago
surwren

Making Concurrent API calls Asynchronously (Is this Correct?)

Apologies for the long code, need to split it up into 2 posts because it's really long:

 async Task SendUserInfoRequestAsync() {
        if (string.IsNullOrEmpty(sessionCache.loginToken)) {
            Debug.LogError("No login token found.....");
            return;
        }
        Uri userInfoUri = new Uri(new Uri(baseUrl), userInfoRoute);
        Uri getUserInfoUri = new Uri(new Uri(baseUrl), getUserInfoRoute);
        
        using (HttpClient client = new HttpClient()) {
            try {
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", sessionCache.loginToken);

                Task<HttpResponseMessage> task1 = client.PostAsync(userInfoUri, null);
                Task<HttpResponseMessage> task2 = client.PostAsync(getUserInfoUri, null);

                HttpResponseMessage response1 = await task1;    
                HttpResponseMessage response2 = await task2;

                if (!response1.IsSuccessStatusCode || !response2.IsSuccessStatusCode) {
                    string errorMessage = "Request from SendUserInfoRequestAsync() failed. ";
                    if (!response1.IsSuccessStatusCode) {
                        lastHttpResponseError = response1;
                        errorMessage += $"First request failed";
                    }
                    if (!response2.IsSuccessStatusCode) {
                        lastHttpResponseError = response2;
                        errorMessage += $"Second request failed.";
                    }
                    Debug.LogError(errorMessage);
                }
Was this page helpful?