{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 运行 CPU 密集型任务\n", "\n", "NiceGUI 提供了一个 `cpu_bound` 函数,用于在单独的进程中运行 CPU 密集型任务。对于那些长时间运行的计算而言,这非常有用,否则这些计算会阻塞事件循环并使 UI 无响应。该函数返回一个可以被等待的 `future`。" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import time\n", "from nicegui import run, ui\n", "\n", "def compute_sum(a: float, b: float) -> float:\n", " time.sleep(1) # simulate a long-running computation\n", " return a + b\n", "\n", "async def handle_click():\n", " result = await run.cpu_bound(compute_sum, 1, 2)\n", " ui.notify(f'Sum is {result}')\n", "\n", "ui.button('Compute', on_click=handle_click)\n", "\n", "# ui.run()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "py311", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.7" } }, "nbformat": 4, "nbformat_minor": 2 }