Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have a little problem. I\'m writing a resource loading and caching system, in

ID: 642712 • Letter: I

Question

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?

Explanation / Answer

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.