Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using(s) inside a loop with a continue

Given the following sample code:

var count = 0;
while (count < 5)
{
    using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
    using (var response = await StaticHttpClient.Client.SendAsync(request))
    {
        if (!response.IsSuccessStatusCode)
        {
            switch ((int)response.StatusCode)
            {
                case 500:
                case 504:
                    continue;
            }
        }
        else
        {  ... }
    }

    count++;
}

Will those IDisposable objects leak memory in this method or will the Dispose method be properly called? (There are many cases missing from the switch and I'm not concerned about the efficiency there).

like image 430
Pete Garafano Avatar asked Jan 12 '23 07:01

Pete Garafano


1 Answers

Will those IDisposable objects leak memory in this method or will the Dispose method be properly called?

The disposables will get Dispose() called on them properly since you used a using statement. When you continue, the Dispose() methods will be called prior to the next iteration of the loop.

like image 195
Reed Copsey Avatar answered Jan 24 '23 07:01

Reed Copsey