tags:

views:

240

answers:

1

Hi all,

I've got some Asynchronous cleanup activity I need to do as my Qt application is shutting down.

My current approach is to trap the aboutToQuit signal. I launch my Asynchronous behavior, and then the application shuts down. Is there any way to block Qt from shutting down until my asynchronous behavior is complete?

This works on windows by trapping the main window's closeEvent and calling ignore() on the event. But on Mac, when a user quits, my ignore() isn't honored, and the Application shuts down before my asynchronous activity is complete.

Thanks.

+1  A: 

Why do you launch your cleanup code asynchronously if you have to wait anyway until your code is done?

If you don't connect your slot as QueuedConnection to aboutToQuit it should block until your cleanup code is done.

But if you really want launch it asynchronously you have to synchronize it by hand:

QSemaphore wait4CleanupDone;

class MyQuitHandler { ... public slots: void handleQuit(); ... } myQuitHandler;
void MyQuitHandler::handleQuit() { ... ; wait4CleanupDone.release(); }

int main(int argc, char** argv) {
  QApplication app(argc, argv);
  QObject::connect(&app, SIGNAL(aboutToQuit()), &myQuitHandler, SLOT(handleQuit()));
  ...
  int result = app.exec();
  wait4CleanupDone.acquire();
  return result;
}

But note, that your asynchronous code might be ignored in some cases anyway:

"We recommend that you connect clean-up code to the aboutToQuit() signal, instead of putting it in your application's main() function. This is because, on some platforms the QApplication::exec() call may not return. For example, on the Windows platform, when the user logs off, the system terminates the process after Qt closes all top-level windows. Hence, there is no guarantee that the application will have time to exit its event loop and execute code at the end of the main() function, after the QApplication::exec() call."

From: http://doc.trolltech.com/4.6/qapplication.html#exec

neverlord
Basically, I needed to make network requests, but didn't want to block Qt while I waited for the response to come in (but didn't want Qt to quit before I had the responses either). We've worked around the issue in another manner entirely, but I'm going to mark your answer as it would be one approach to solve the issue...
Noah Callaway