I am wanting to create an internal messaging system that can tell me the duration of some code being called. I was thinking for ease of use, to make the SystemMessage class implement IDisposable.
I would set a time stamp during the SystemMessage's constructor and if the Dispose was called, I could figure out the duration.
The problem is that I do not want to have the object GC'ed. I want it to stay around as part of a MessageCollection.
Is there another construct in C# that can give me the usability of the Using Statement without stepping on the intended function of 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?
I don't think using is what you want here. Why not just have the constructor record the time, and then when DownloadAFile is called log the time delta? In your example, if there's an exception, it will log the time of the exception as though the file was downloaded then.
If you actually want the behavior to be like your example, just use a try / finally block, and do the logging in the finally.
usingis just syntactic sugar for a try / finally block and a call toDispose.The equivalent code to your example looks like this: