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?
Well, this is an oldie, but nobody else seems to have posted the answer which I think is the best style (from what I understand of your requirements):
The important point being that
CreateNewTimedMessage
might as a side-effect create and store a semi-permanentMessage
object, but it returns a temporary timing object (that usesStopWatch
, or some similar mechanism) which doesn't survive the scope of theusing
block. (It's ok for theMessageTimer
to reference theMessage
, but not the reverse.)So disposal of the
MessageTimer
object might have a side-effect of logging the final time somewhere, but the object itself won't survive or be resurrected; this isn't an abuse of theusing
construct because you really are disposing of an object.(The actual implementation of the
MessageTimer
would probably be similar to Joe's answer.)