我想创建一个内部消息系统,可以告诉我一些代码被调用的持续时间.我在考虑易用性,以使SystemMessage类实现IDisposable.
我会在SystemMessage的构造函数中设置一个时间戳,如果调用了Dispose,我可以计算出持续时间.
问题是我不希望GC对象.我希望它作为MessageCollection的一部分留在身边.
在C#中是否有另一个构造可以在没有踩到IDisposable的预期功能的情况下为我提供Using语句的可用性.
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?
Run Code Online (Sandbox Code Playgroud)