Keeping GUIs responsive during long-running tasks

前端 未结 9 2116
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-14 22:28

Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming.

Here\'s a good discussion of h

9条回答
  •  情书的邮戳
    2020-12-14 23:14

    Threads - Let's use a simple 2-layer view (GUI, application logic).

    The application logic work should be done in a separate Python thread. For Asynchronous events that need to propagate up to the GUI layer, use wx's event system to post custom events. Posting wx events is thread safe so you could conceivably do it from multiple contexts.

    Working in the other direction (GUI input events triggering application logic), I have found it best to home-roll a custom event system. Use the Queue module to have a thread-safe way of pushing and popping event objects. Then, for every synchronous member function, pair it with an async version that pushes the sync function object and the parameters onto the event queue.

    This works particularly well if only a single application logic-level operation can be performed at a time. The benefit of this model is that synchronization is simple - each synchronous function works within it's own context sequentially from start to end without worry of pre-emption or hand-coded yielding. You will not need locks to protect your critical sections. At the end of the function, post an event to the GUI layer indicating that the operation is complete.

    You could scale this to allow multiple application-level threads to exist, but the usual concerns with synchronization will re-appear.

    edit - Forgot to mention the beauty of this is that it is possible to completely decouple the application logic from the GUI code. The modularity helps if you ever decide to use a different framework or use provide a command-line version of the app. To do this, you will need an intermediate event dispatcher (application level -> GUI) that is implemented by the GUI layer.

提交回复
热议问题