When is the correct time to call FreeLibraryWhenCallbackReturns?

Raymond

When is the correct time to call Free­Library­When­Callback­Returns, or any of the other ...When­Callback­Returns functions? In practice, many people call the function immediately before returning from the callback. Is this a requirement?

No. You can call the ...When­Callback­Returns function at any time during the execution of your callback, but you can call each one at most once per callback instance. In other words, you cannot ask for two DLLs to be freed when the callback returns, but it’s okay to ask for one DLL to be freed and one critical section to be exited. If you do ask for multiple things to happen when the callback returns, the order in which they occur is unspecified.

By convention, the ...When­Callback­Returns function is called immediately before the callback returns, because it matches the point at which you would have called the non-...When­Callback­Returns version. In other words, “I would have called Free­Library or Free­Library­And­Exit­Thread here, but I can’t, so I’ll call Free­Library­When­Callback­Returns instead, and then immediately return.”

Of course, if you are worried that you might forget to call Free­Library­When­Callback­Returns in all your exit paths (a legitimate concern, in my opinion), you may choose to call it at the start of the work, so that you won’t forget. It doesn’t matter when you call it, as long as you do it inside the task at some point before you return.

Many happy returns. (Tomorrow is Boxing Day, you see.)

0 comments

Comments are closed. Login to edit/delete your existing comments