Reputation: 2414
I have built a desktop kivy application with some methods that perform changes in my app as well as other calculations that take some time (around 30 seconds). When I call these methods, the app freezes during their execution, which is not desirable. Is there a way to prevent the app from freezing and instead display some kind of popup with an animated gif, so that the user knows the app is processing something and did not crash/stop responding?
I have tried to use multiprocessing to run these methods in the background while an informative Popup appears, but these processes do not share memory and data structures with the main app process. So, even though the method run successfully and the popup was shown, there were no changes in the app...
Anyway, this is the multiprocessing code:
def run_in_background(self, func, *args):
def run_func(m, a):
# Execute the function with args
m(*a)
def check_process(proc, dt):
if not proc.is_alive():
Clock.unschedule(check_func)
self.dismiss_popup()
# Create background process and start it
p = multiprocessing.Process(target=run_func, args=(func, args))
p.start()
# Create waiting dialog
content = CrunchData()
# Show waiting popup
self.show_popup(title="Some title", content=content, size=(400, 300))
# Create schedulled check for process state
check_func = partial(check_process, p)
Clock.schedule_interval(check_func, .1)
Any help would be much appreciated.
Upvotes: 1
Views: 3707
Reputation: 8213
You've got a good start to your problem, but polling is_alive is not what you want to do. Since you are only doing one background task and showing a dialog, you could use either threading OR multiprocessing for this. Their API is very similar.
To avoid polling, you can use a processing pool (easier to deal with) and pass a callback to pool.apply_async
.
This callback will not be run on the main thread, though, so if you need to run code on the main thread you will need to schedule it in your callback.
An alternative is just to use a separate thread instead of process, and use Kivy's clock to schedule a function call at the end of the thread function. See kivy threading docs.
This SO answer is also an option for transferring data from a thread to the main thread: https://stackoverflow.com/a/22033066. It's from a Kivy dev.
Upvotes: 1