In continuation to the this question, what I want to do is retry calling the same Web API call 3 times if the task is getting cancelled , as it only throws error sometimes and not every time.
I have written something as below:
int maxattempts = 3;
int attemptcount = 1;
try
{
LogMessage("JobURL call start 1st time");
response = await SendHttpRequest();
LogMessage("JobURL call end");
}
catch (TaskCanceledException tex)
{
attemptcount++;
if (attemptcount < maxattempts){
LogMessage("JobURL call start " + attemptcount.toString() + " time...");
response = await SendHttpRequest();
}
}
catch (Exception ex2)
{
LogMessage("Exception Details : " + ex2.Message);
LogMessage("Exception StackTrace : " + ex2.StackTrace);
}
I'm throwing exception from SendHttpRequest()
method and in the calling method, I'm checking the type of exception and calling the same method again if it is TaskCanceledException
. Now I want to try like this for 3 times before giving up.
So should I write try catch again in the catch block for third attempt. I somehow feel that it is very crude way of writing the code. Can anyone guide me how to write this in a efficient way? Many thanks!