【发布时间】:2009-05-01 18:06:21
【问题描述】:
我想创建一个内部消息传递系统,它可以告诉我某些代码被调用的持续时间。我在考虑易于使用,使 SystemMessage 类实现 IDisposable。
我会在 SystemMessage 的构造函数期间设置一个时间戳,如果调用了 Dispose,我可以计算出持续时间。
问题是我不想让对象 GC'ed。我希望它作为 MessageCollection 的一部分保留。
C# 中是否有另一种结构可以让我使用 Using 语句,而无需踩到 IDisposable 的预期功能。
Using (message = Collection.CreateNewMessage("FileDownlading"))
{
// I wonder how long it is taking me to download this file in production?
// Lets log it in a message and store for later pondering.
WebClass.DownloadAFile("You Know This File Is Great.XML");
}
// we fell out of the using statement, message will figure out how long
// it actually took to run.
// This was clean and easy to implement, but so wrong?
【问题讨论】:
-
using 块的目的是在对象超出范围时将其处理掉。你应该用它做任何其他事情。
-
迈克尔,我同意。是否有另一种可以以这种方式使用的 C# 构造?
标签: c# idisposable using misuse