It's not clear from your question, but it sounds like the module cannot be unloaded because it is actively executing a command that is waiting for user input. So, I think you are asking how to postpone the unloading until the command is finished executing. The answer to that question is to use ads_queueexpr() to queue the (arxunload "XXX") function from within the command itself.
However, you are creating much bigger problems for yourself by attempting to unload the module. Unloading takes time, so it most certainly does not help performance. The correct solution to your problem is to not unload your modules and leave the unloading to AutoCAD.