Handling user interface in a multi-threaded application (or being forced to have a UI-only main thre

Posted by Patrick on Stack Overflow See other posts from Stack Overflow or by Patrick
Published on 2010-03-13T11:06:16Z Indexed on 2010/03/13 11:15 UTC
Read the original article Hit count: 255

In my application, I have a 'logging' window, which shows all the logging, warnings, errors of the application. Last year my application was still single-threaded so this worked [quite] good.

Now I am introducing multithreading. I quickly noticed that it's not a good idea to update the logging window from different threads. Reading some articles on keeping the UI in the main thread, I made a communication buffer, in which the other threads are adding their logging messages, and from which the main thread takes the messages and shows them in the logging window (this is done in the message loop).

Now, in a part of my application, the memory usage increases dramatically, because the separate threads are generating lots of logging messages, and the main thread cannot empty the communication buffer quickly enough. After the while the memory decreases again (if the other threads have finished their work and the main thread gradually empties the communication buffer).

I solved this problem by having a maximum size on the communication buffer, but then I run into a problem in the following situation:

  • the main thread has to perform a complex action
  • the main thread takes some parts of the action and let's separate threads execute this
  • while the seperate threads are executing their logic, the main thread processes the results from the other threads and continues with its work if the other threads are finished

Problem is that in this situation, if the other threads perform logging, there is no UI-message loop, and so the communication buffer is filled, but not emptied.

I see two solutions in solving this problem:

  • require the main thread to do regular polling of the communication buffer
  • only performing user interface logic in the main thread (no other logic)

I think the second solution seems the best, but this may not that easy to introduce in a big application (in my case it performs mathematical simulations).

Are there any other solutions or tips? Or is one of the two proposed the best, easiest, most-pragmatic solution?

Thanks, Patrick

© Stack Overflow or respective owner

Related posts about Windows

Related posts about multithreading