When is the correct time to call
FreeLibraryWhenCallbackReturns
,
or any of the other ...WhenCallbackReturns
functions?
In practice,
many people call the function immediately before
returning from the callback.
Is this a requirement?
No.
You can call the
...WhenCallbackReturns
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
...WhenCallbackReturns
function
is called immediately before the callback returns,
because it matches the point at which you would have
called the non-...WhenCallbackReturns
version.
In other words,
“I would have called
FreeLibrary
or
FreeLibraryAndExitThread
here,
but I can’t,
so I’ll call
FreeLibraryWhenCallbackReturns
instead, and then immediately return.”
Of course, if you are worried that you might forget to call
FreeLibraryWhenCallbackReturns
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.)