Rya*_*ies 3 c# windows resources
C#3.5,Windows 7+
以下面的代码为例:
using (RegistryKey regKey = Registry.Users.OpenSubKey(regKeyString, true))
{
if (polRegKey.GetValue("Foo") == null)
polRegKey.CreateSubKey("Foo");
}
Run Code Online (Sandbox Code Playgroud)
现在假设我每秒都在循环中执行此代码.
然后,当我使用Process Explorer查看正在运行的进程时,我看到的是生成该注册表项的新句柄,但未及时销毁.相反,我看到的是每秒创建一个新句柄,然后在大约20秒之后,几乎所有句柄的大块同时被破坏.这是我期望从垃圾收集器那种行为.我认为C#的using语句自动处理对象我错了吗?它似乎是以一种非常懒惰的方式做到的,如果它实际上是在做它的话.
你没有处置的价值 polRegKey.CreateSubKey("Foo");.
using (RegistryKey regKey = Registry.Users.OpenSubKey(regKeyString, true))
{
if (polRegKey.GetValue("Foo") == null) {
using (polRegKey.CreateSubKey("Foo")) {
Console.Writeline("Key Created! You could also call Dispose()!");
}
}
}
Run Code Online (Sandbox Code Playgroud)