Resolved HttpClient Response IsSuccessStatusCode firing twice?

ConsKa

Well-known member
Joined
Dec 11, 2020
Messages
140
Programming Experience
Beginner
I have the following code and I cannot for the life of my answer why it is firing twice....

C#:
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();

request.RequestUri = new Uri(shortUrl);
request.Method = HttpMethod.Get;
request.Headers.Add("Key", api);
HttpResponseMessage response = await httpClient.SendAsync(request);

If (!response.IsSuccessStatusCode)
{
    httpClient.Dispose();
    aTimer.Stop();
    ErrorMessage();
}

ErrorMessage pushes out a MessageBox.Show("Error")....I created the method simply to see if I could bypass this error.

Using break points I go to teh If statement, it fires, there is an error, it moves through and down to error message...it goes back to the top of the IF statement.

This happens if I have the method or simply "MessageBox.Show("Error")....

I do not understand why it is going back to the IF statement and testing twice?
 
ok, I found the issue, though this was not clear using the break points.

I have a timer set up to run the program every two minutes, and that calls the method....for some reason it was going back to that (although not referenced nor going through it via breakpoints) and firing the entire method again - none of this was clear, it simply went back to the IF statement.

Taking the method out of the Timer set up fixes the issue.

Wild guesses for the win.
 
Depending on the type of timer you are using, some of the timer tick/elapsed events are re-entrant.

Also as as aside, beware about disposing HttpClient:
 
Cheers for that a good read.

Using MVVM I am more likely to hit another HttpClient in a different ViewModel, as this is a simple one time get every 2 minutes that is disposed of at the end of each get process.

I know how to put the entire thing inside a Model and call it from there - which I think has the same effect as being discussed in that thread - using a static HttpClient for all calls rather than creating one for each.
 
Back
Top Bottom