using 块是否创建并维护 GC 的引用?

发布于 2024-08-22 20:29:19 字数 434 浏览 4 评论 0原文

这主要是出于好奇,因为有更好的方法来实现我能想到的这种构造的几乎所有用例(至少在我经常使用的 C# 和其他语言中),但我最近在这里看到了 作用域互斥体一个很酷的概念。

我的问题是,using 语句是否维护对其所作用的对象的引用(即:阻止 GC 运行)?

例如,如果我这样做:

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

ScopedMutex 对象是否会在 using 块结束时保持其存在,或者 GC 是否可以在块中运行并处理它?

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 cool 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

皓月长歌 2024-08-29 20:29:19

不,GC 不会处置它。对该对象的引用存储在局部变量中(有关详细信息,请参阅此答案)。局部变量被视为 GC 根,并且可以从它访问该对象(using 块需要可以访问该对象才能对其调用 Dispose)。

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).

风吹雨成花 2024-08-29 20:29:19

C# 编译器将隐式为您创建一个变量。 using 语句在编译时实际上会转换为如下内容(您可以使用 Redgate Reflector< /a> 亲自查看确切的代码,顺便说一句):

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

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();
}
沩ん囻菔务 2024-08-29 20:29:19

它不会将其处置在区块中间。

It will not dispose it in mid-block.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文