Hello friends,
There is a 3rd party web API that returns game codes. A single request can return a max of 10 codes. I am calling an asp.net core web API of mine as follows in a worker. (The worker and my API are on the same server.) Basically, I'm sending requests to process 100 codes and return them.
My web API is cut into small pieces (10) and calls this 3rd party web API.
I couldn't visualize the solution how to check if there is a problem with one of your requests from the 3rd party web API. How should I handle it in Parallel.ForEachAsync? I mean let's say I want 100 codes (quantity), I am sending the requests to the 3rd party service 10 by 10. How to deal with an error let's say in the 4th request in the while loop?
Thank you.
There is a 3rd party web API that returns game codes. A single request can return a max of 10 codes. I am calling an asp.net core web API of mine as follows in a worker. (The worker and my API are on the same server.) Basically, I'm sending requests to process 100 codes and return them.
C#:
var num = amount;
var firstNum = 50;
var secondNum = 50;
if (num < 100)
{
firstNum = (num + 1) / 2;
secondNum = num - firstNum;
}
var quantities = new List<int> { firstNum, secondNum};
var cts = new CancellationTokenSource();
ParallelOptions parallelOptions = new()
{
MaxDegreeOfParallelism = 2,
CancellationToken = cts.Token
};
try
{
await Parallel.ForEachAsync(quantities, parallelOptions, async (quantity, ct) =>
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("productCode", productCode),
new KeyValuePair<string, string>("quantity", quantity.ToString()),
new KeyValuePair<string, string>("clientTrxRef", bulkId.ToString())
});
using var response =
await httpClient.PostAsync(_configuration["Razer:Production"], content, ct);
if ((int)response.StatusCode == 200)
{
var coupon = await response.Content.ReadFromJsonAsync<Root>(cancellationToken: ct);
_logger.LogInformation("REFERENCE ID: {referenceId}", coupon.ReferenceId);
await UpdateData(id);
}
else
{
_logger.LogError("Purchase ServiceError: {statusCode}",
(int)response.StatusCode);
}
});
}
catch (OperationCanceledException ex)
{
_logger.LogError("Operation canceled: {Message}",
ex.Message);
}
My web API is cut into small pieces (10) and calls this 3rd party web API.
Web API:
while (requestedAmount > 0)
{
var gameRequest = _mapper.Map<RequestDto, GameRequest>(requestDto);
var count = Math.Min(requestedAmount, 10);
gameRequest.quantity = count;
...
I couldn't visualize the solution how to check if there is a problem with one of your requests from the 3rd party web API. How should I handle it in Parallel.ForEachAsync? I mean let's say I want 100 codes (quantity), I am sending the requests to the 3rd party service 10 by 10. How to deal with an error let's say in the 4th request in the while loop?
Thank you.