This is different from this one because in that case the warning was valid. In this case, the warning is invalid as per the accepted answer. I saw that question when I was looking for answers, it does not answer this one.
Given the following code:
internal List<PaletteClass> GetPaletteList( int userId )
{
using(var stashEntities = new StashEntities<StashClass>())
using(var paletteEntities = new PaletteEntities<PaletteClass>())
{
var paletteList = from palette in paletteEntities.Palettes
from stash in stashEntities.Stashes
where palette.UserId == userId && stash.StashId == palette.StashId
select palette;
return paletteList.ToList();
}
}
Where StashEntities and PaletteEntities inherit from DBContext, I get the warning 'Access to disposed closure' referring to stashEntities as shown in the image below.
I know that this is meant to safeguard against cases where the expression is evaluated after a parameter goes out of scope. But, in this case the expression is assigned to a list within the usings so stashEntities should be in scope.
Note that if I swap the expression as follows:
var paletteList = from stash in stashEntities.Stashes
from palette in paletteEntities.Palettes
where palette.UserId == userId && stash.StashId == palette.StashId
select palette;
return paletteList.ToList();
then ReSharper moves the warning to paletteEntities.
Question: Is this ReSharper warning something to worry about in this case or should I just add the ReSharper comment to ignore for this line?
Bonus Question (if answer to previous question is ignore): What if I just returned paletteList without calling ToList() and forcing the expression to be evaluated? The fact that ReSharper does not worry about paletteEntities (in the original example) makes me think that there is something going on to keep it in scope, would the same apply to stashEntities and all would be OK?
Update / Simplification
As shown in the image below, even if only one DBContext (stashPaletteEntities) is used, I get the same message which means that the accepted answer is correct - this is a bug in ReSharper. If the first line referring to stashPaletteEntities is OK, the second should be too.
This is something that has been a bug in ReSharper for quite a while, as described in their dev board. Unfortunately it's been an issue since 6.1.
Unfortunately, ReSharper analysis is not smart enough to track that query expression is definitely executed inside "using ..." block. For now, it tracks only in a single expression.
We are going to increase smartness in the future releases
Essentially, the analysis engine can only match one from
up with one using
within a single expression. It won't affect the functionality of the code; only the warning, and it's perfectly safe to ignore. Removing the .ToList()
wouldn't affect the parsing of the expression tree.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With