Connection lost issue when calling long running function #3115
-
QuestionIn NiceGUI, I've encountered the following issue: I have considered two solutions to address this problem: ### Solution 1: Utilize Multi-Threading ### Solution 2: Asynchronous Programming I would like to determine which solution is preferable, or if there are any other recommended approaches to the issue described above. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 8 replies
-
Please read https://github.com/zauberzeug/nicegui/wiki/FAQs#why-is-my-long-running-function-blocking-ui-updates. It should answer your question pretty well. |
Beta Was this translation helpful? Give feedback.
-
Thanks rodja. i understand the reason why this is happening though I am trying to figure out the best/simple solution. Looks like the solution proposed is solution#2 above which has challenges if we want to leverage 3rd party libraries which do not support asycn ops. However, I also got another solution which I want to get feedback from community, if they see any problem with this: ### Solution3: Use the asyncio library The asyncio library provides a run_in_executor function, which allows running synchronous code within an asynchronous function. # asyncio calling code
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, long_running_operation) Additionally, I've used a ui.timer to monitor whether the result has been determined, similar to Solution 1 mentioned above When the ui.timer is positioned above the asyncio calling code, everything functions smoothly. This give me concerns if solution#3 has any unintended consequences that I am not grasping. |
Beta Was this translation helpful? Give feedback.
-
A hack that worked for me, was to just increase the default timeout duration when that pop-up shows on the UI using reconnect_timeout parameter. |
Beta Was this translation helpful? Give feedback.
Sorry, I should have mentioned the import:
Oh and I forgot to copy&paste the
run_in_executor
line which actually callssync_func
. I updated my code above.Yes,
ui.timer
is also a common method to trigger a background task. But make sure to setonce=True
to avoid repeating the task every 1 second: