I just got burned by using callbacks in a multi-threaded app. I've rewritten the part to avoid callbacks, but for my good-deed-of-the-day, I wanted to issue a word of warning.
Before you can safely use a callback / delegate / virtual function, particularly in multi-threaded code, you should answer the following questions:
The questions really could be endless. If you're code-reviewing somebody else's code that uses callbacks, these are great questions to ask.
And it applies to managed code too:Also beware, Virtual functions are basically callbacks. In C#, delegates and events are callbacks, but with a pretty syntax than C++ function pointers.
Callbacks and ICorDebugThe regular reader may realize that ICorDebug uses callbacks to invoke managed debug events (via ICorDebugManagedCallback), and we definitely hit some of these issues. For example, what if you try to Detach() during the middle of a callback? Calling Continue() within a callback vs. outside a callback exercise very different code-paths. These corner cases caused us extra grief when implementing ICorDebug. Since ICD doesn't have nice short answers here, I'll blog about that separately.