2

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 { if(Finished) value(); else m_LoadFinished+=value; } } 

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?

1
  • 1
    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#. Commented Apr 6, 2011 at 13:14

2 Answers 2

2

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.

1

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. ;)

1
  • That depends on your definition of clever. Mine is quite different from obscure and obfuscated. Commented Aug 4, 2014 at 15:59

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.