在IDisposable对象上使用语句-调用Dispose方法的延迟 [英] using statement on IDisposable object - delay of calling Dispose method

查看:106
本文介绍了在IDisposable对象上使用语句-调用Dispose方法的延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文章所述,有关在IDisposable上使用的用法对象,它说了一个有趣的词:

As describe this article, about usage of using on IDisposable objects, it says one interesting words:

...使用块,在块结束后的某个时间自动调用Dispose方法. (它可能不是立即的;它取决于CLR.)

...using block, the Dispose method is automatically called sometime after the block ends. (It may not be immediate; it depends on the CLR.)

有趣的是"它可能不是立即的;取决于CLR ". 任何人都可以提供更多详细信息吗?因为我们有一些奇怪的情况,似乎在使用(new MyDisposable()){...}的代码上,在代码块结束之后,它确实 NOT 不会立即在MyDisposable实例上调用Dispose方法,但是时间过后.

Interesting here is "It may not be immediate; it depends on the CLR". Can anyone provide more details on this? Because we have some strange situations where it seems that on code using(new MyDisposable()) {...}, after end of block } it does NOT immediately calls Dispose method on MyDisposable instance, but some time later.

更新:对我而言,结论在我看来在其他地方也有问题.我认为Dispose方法可以在使用块结束后的一段时间内调用.但是,如果不是那样,那么我必须在代码的其他地方发现问题. 感谢您的回复!

UPDATE: Conclusion for me, it seems to me that i have problem elsewhere. I think that Dispose method can be called some time later after using block ends. But when it is not like that, than i must find problem somewhere else in my code. Thanks for responses!

推荐答案

我对该声明略有怀疑,并认为它们还意味着其他含义(也许是垃圾回收). using语句只是try/finally块的语法糖,而try/finally块则放置了finally块.鉴于此C#:

I'm a little skeptical of that statement, and think they meant something else (perhaps garbage collection). A using statement is just syntactic sugar for a try/finally block where the finally block calls dispose. Given this C#:

using (var fs = new FileStream("C:\\blah.txt", FileMode.CreateNew))
{
    fs.WriteByte(7);
}

IL看起来像这样:

//snipped
L_000e: nop 
L_000f: ldstr "C:\\blah.txt"
L_0014: ldc.i4.1 
L_0015: newobj instance void [mscorlib]System.IO.FileStream::.ctor(string, valuetype [mscorlib]System.IO.FileMode)
L_001a: stloc.0 
L_001b: nop 
L_001c: ldloc.0 
L_001d: ldc.i4.7 
L_001e: callvirt instance void [mscorlib]System.IO.Stream::WriteByte(uint8)
L_0023: nop 
L_0024: nop 
L_0025: leave.s L_0037
L_0027: ldloc.0 
L_0028: ldnull 
L_0029: ceq 
L_002b: stloc.1 
L_002c: ldloc.1 
L_002d: brtrue.s L_0036
L_002f: ldloc.0 
L_0030: callvirt instance void [mscorlib]System.IDisposable::Dispose()
L_0035: nop 
L_0036: endfinally 
L_0037: nop 
L_0038: nop 
L_0039: ret 
.try L_001b to L_0027 finally handler L_0027 to L_0037

最后一行的通知仅是.try和.finally. C#规范中也指出了这一点: http://msdn.microsoft.com/zh-CN/library/aa664736.aspx

Notice on the last line it's just a .try and .finally. This is also indicated in the C# spec: http://msdn.microsoft.com/en-us/library/aa664736.aspx

这篇关于在IDisposable对象上使用语句-调用Dispose方法的延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆