views:

1183

answers:

3

I have a class that downloads, examines and saves some large XML files. Sometimes I want the UI to tell me what's going on, but sometimes I will use the class and ignore the events. So I have placed lines of code like this in a dozen places:

RaiseEvent Report("Sending request: " & queryString)

RaiseEvent Report("Saving file: " & fileName)

RaiseEvent Report("Finished")

My question is this - will these events slow down my code if nothing is listening for them? Will they even fire?

A: 

There might be a small amount of overhead, but I wouldn't worry about it. Certainly the actual action is going to be the performance driver.

As a side note: raising an event with no handlers in C# actually causes an exception to be thrown. VB.Net doesn't have this problem :)

Joel Coehoorn
+4  A: 

There is no magic, the code hiding under RaiseEvent does exactly what you'd expect, it iterates through a collection of handlers, and executes each one. The overhead of checking to see are there any handlers is trivial, don't worry about it.

If your REAL question is "To save time, should I check that the events have handlers before raising the events?" . . . then the answer is "No", you'll gain nothing by doing this.

Also, don't worry about optimisation unless you need to (see this Wikipedia entry to see why.)

Re: Calling GetMystring().

Yes, this ties in with how you raise events in C#, where you check for the existence of handlers before raising the event. E.g.:

if (MyEvent != null)
    MyEvent(GetMyString())

Nice experiment by the way :)

Binary Worrier
First, thanks for the direct answer to the question. Second, you make a good point about optimization. "Code Complete (2nd Edition) by Steve McConnell has a chapter (25) on code tuning that basically says "Don't optimize unless you absolutely have to, and be conscious of the trade-offs involved."
Shane
+4  A: 

My own answer:

In VB.NET the event does NOT fire if there are no handlers set up to listen for it.

I did a little experiment where the code that raises the event passes the result of a function, and that function only executed when there was an event handler set up to handle the event.

RaiseEvent Report(GetMyString())

In other words, I am saying that the GetMystring function above does not get called unless handlers actually exist.

Shane
@Shane: I updated my answer with that in mind. Thanks.
Binary Worrier
Actually, you should mark this (your own) entry as the answer, which it is.
Binary Worrier