{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 运行 I/O 密集型任务\n", "\n", "NiceGUI 提供了一个 `io_bound` 函数,用于在单独的线程中运行 I/O 密集型任务。对于那些长时间运行的 I/O 操作而言,这非常有用,否则这些操作会阻塞事件循环并使 UI 无响应。该函数返回一个可以被等待的 future。" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import requests\n", "from nicegui import run, ui\n", "\n", "async def handle_click():\n", " URL = 'https://httpbin.org/delay/1'\n", " response = await run.io_bound(requests.get, URL, timeout=3)\n", " ui.notify(f'Downloaded {len(response.content)} bytes')\n", "\n", "ui.button('Download', 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 }