Convert to 'using' declaration (extends resource lifetime)

There are two conversions enabling the new c# 8.0 feature of using declarations. One is straight forward:

Convert to 'using' declaration

The other is less straight forward:

Convert to 'using' declaration (extends resource lifetime)

Well it is clear what is meant by it, but not how bad that is.

Take the following example:

await using (SqlDataReader reader = await SqlHelperAsync.ExecuteReaderAsync(Config.DbConnectionString, CommandType.Text, sqlQuery))
{

     while (reader.Read())
    {

        .....

    }

}

return Answers;

Converting this to a 'using' declaration extends the lifetime of the resource until after the return Answers. But how bad is that?

Is there some guidance when a using declaration should not be used in view of the resource lifetime?

0
4 comments
Official comment

Hello Pieter,

 

Well generally you shouldn't extend resource lifetime if the code below the using statement depends on the resource disposal.

Let's say you have the following code:

using ( /* acquire file */ )
{
 /* perform first file operation */
}

using ( /* acquire the same file */ )
{
 /* perform another file operation */
}

If you turn this code into:

using var /* acquire file */

/* perform first file operation */


using ( /* acquire the same file */ )
{
 /* perform another file operation */
}

then it may not be working as before because code performing another file operation expects the file to be released after performing first file operation.

Thank you.

Thank you, that is clear.

But there are no performance or garbage collection considerations to worry about?

0

Angelina Elycheva

So why am I getting a R# warning about stacked usings?

Resharper wants to change this...

using (var request = new HttpRequestMessage(HttpMethod.Post, new Uri(ApiBaseUrl + "/Run")))
using (var httpContent = CommonHelper.CreateHttpContent(payload))
{
//does stuff
}

//into this...
using var request = new HttpRequestMessage(HttpMethod.Post, new Uri(ApiBaseUrl + "/Run"));
using (var httpContent = CommonHelper.CreateHttpContent(payload))
{
//does stuff
}                 

Which seems to be counterintuitive to both me and your description.

0

Hi Andrew,

It is a known issue RSRP-482303.

Please vote or leave a comment to subscribe to the issue and receive updates.

0

Please sign in to leave a comment.