开发者

Does a using block create and maintain a reference for the GC?

开发者 https://www.devze.com 2022-12-21 00:12 出处:网络
This is mostly for curiosity\'s sake, as there are better ways of implementing almost any use case I can think of for this construct (in C# and other languages I use regularly, at least), but I recent

This is mostly for curiosity's sake, as there are better ways of implementing almost any use case I can think of for this construct (in C# and other languages I use regularly, at least), but I recently saw on here a scoped mutex which was a coo开发者_如何学Cl concept.

My question is, does the using statement maintain a reference (ie: prevent the GC from running on) to the object it's acting on?

For example, if I were to do:

using (new ScopedMutex())
{
// ...
}

would the ScopedMutex object maintain its existence to the end of the using block, or could the GC run and dispose of it mid-block?


No, the GC will not dispose it. A reference to that object is stored in a local variable (see this answer for more info). A local variable is considered a GC root and the object will be reachable from it (it needs to be reachable for the using block to be able to call Dispose on it).


The C# compiler will implicitly create a variable for you. The using statement would actually be transformed into something like the following when compiled (you can use Redgate Reflector to see the exact code for yourself, btw):

ScopedMutex scopedMutex1 = new ScopedMutex();
try
{
    // ...
}
finally
{
    scopedMutex1.Dispose();
}


It will not dispose it in mid-block.

0

精彩评论

暂无评论...
验证码 换一张
取 消