December 25th, 2015

When is the correct time to call FreeLibraryWhenCallbackReturns?

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

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.