Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a little problem. I'm writing a resource loading and caching system, in which user can request a resource, and set a callback to be called when resource is loaded (and/or wait for load to finish). This leads to code like this:

var waitobj=Loader.RequestObject("foo");
waitobj.LoadFinished+=delegate{ Bar(); };

However, since resources are cached, the call to RequestObject may actually complete synchronously. This means that when callback is set, request is already finished, and callback is never called. I thought up a clever trick: let's just check the state of request in the event adder itself!

public event LoadFinishedHandler LoadFinished {
    add {

This will call the callback function no matter what.. but my coworkers said that this method is too complicated and no one will be able to maintain this code. I like this trick anyway, but I'm obviously biased.

What do you think, is this trick too clever for its own good?

share|improve this question
You might want to consider using IAsyncResult, BeginXXX and EndXXX. This is unmaintainable due to the fact that it doesn't adhere the idioms that are common in C#. – the_drow Apr 6 '11 at 13:14
up vote 2 down vote accepted

I can see where your colleagues are coming from. That seems like a dangerous approach.

Most people in this situation would do something like this:

Loader.BeginRequestObject("foo", Bar);

BeginRequestObject then kicks off a thread to do whatever it is you're doing in RequestObject and then returns immediately. When the thread completes, it calls Bar().

This is much more solid than the event model for these kinds of situations. The event model is more useful in cases where you have an object with many listeners (who can hook in before the thread even begins) who are all interested in knowing when events happen during the process.

share|improve this answer

There's an old adage:

"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." --Brian Kernighan

Look into what that could mean for your code. ;)

share|improve this answer
That depends on your definition of clever. Mine is quite different from obscure and obfuscated. – Dan Aug 4 '14 at 15:59

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.