蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验事件循环队列顺序、Future 三态与并发耗时、then 链及异步 try/on/catch

PYTHONWindows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。explore-async.py
explore-async.py207 行
"""Offline Dart 3.x semantic verification lab for Chapter 18 (async)."""
import asyncio
from collections import deque
import json

VERSION = "CPython 3.12.14 offline Dart 3.x semantic verifier (dart SDK absent)"


def case_sync_blocking_vs_async_event_loop():
    # Exact Dart single-isolate event loop model: sync -> microtask queue -> event queue
    log = []
    microtasks = deque()
    events = deque()

    log.append("程序开始")
    events.append(lambda: log.append("收到结果: 异步结果"))
    microtasks.append(lambda: log.append("微任务优先于事件队列"))
    log.append("Future 已创建,但还没完成")
    log.append("程序继续执行...")

    while microtasks or events:
        while microtasks:
            microtasks.popleft()()
        if events:
            events.popleft()()

    expected = {
        "execution_order": [
            "程序开始",
            "Future 已创建,但还没完成",
            "程序继续执行...",
            "微任务优先于事件队列",
            "收到结果: 异步结果",
        ],
    }
    actual = {"execution_order": log}
    return {
        "name": "sync_blocking_vs_async_event_loop",
        "summary": "校验 Dart 单 Isolate 事件循环执行顺序:同步代码 → 微任务队列 → 事件队列 Future 回调",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_future_states_and_async_await_parallel():
    async def run():
        # Virtual latency tracking (deterministic, zero real sleep)
        async def fetch_name(uid: int) -> tuple[str, int]:
            await asyncio.sleep(0)
            return f"用户{uid}", 1000

        async def fetch_age(uid: int) -> tuple[int, int]:
            await asyncio.sleep(0)
            return 20 + uid, 500

        # Sequential await
        n1, t1 = await fetch_name(1)
        a1, t2 = await fetch_age(1)
        seq_ms = t1 + t2

        # Concurrent Future.wait (asyncio.gather)
        (n2, pt1), (a2, pt2) = await asyncio.gather(fetch_name(2), fetch_age(2))
        par_ms = max(pt1, pt2)

        # Future 3 states via asyncio.Future
        fut_ok = asyncio.get_running_loop().create_future()
        state_uncompleted = not fut_ok.done()
        fut_ok.set_result("done_value")
        state_data = fut_ok.done() and fut_ok.exception() is None

        fut_err = asyncio.get_running_loop().create_future()
        fut_err.set_exception(RuntimeError("boom"))
        state_error = fut_err.done() and fut_err.exception() is not None
        _ = fut_err.exception()

        return {
            "states": {
                "uncompleted": state_uncompleted,
                "completed_with_data": state_data,
                "completed_with_error": state_error,
            },
            "sequential": {"user": f"{n1}:{a1}", "virtual_ms": seq_ms},
            "parallel_wait": {"user": f"{n2}:{a2}", "virtual_ms": par_ms},
        }

    actual = asyncio.run(run())
    expected = {
        "states": {
            "uncompleted": True,
            "completed_with_data": True,
            "completed_with_error": True,
        },
        "sequential": {"user": "用户1:21", "virtual_ms": 1500},
        "parallel_wait": {"user": "用户2:22", "virtual_ms": 1000},
    }
    return {
        "name": "future_states_and_async_await_parallel",
        "summary": "验证 Future 三种状态与顺序 await(1500ms)相比 Future.wait 并发(1000ms)的耗时优势",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_then_catcherror_whencomplete_chain():
    def run_chain(url: str) -> list[str]:
        trace = ["开始请求..."]
        try:
            if not url:
                raise ValueError("URL 不能为空")
            data = f"来自 {url} 的数据"
            trace.append(f"then1:{data}")
            processed = f"处理后的: {data}"
            trace.append(f"then2:{processed}")
        except Exception as exc:
            trace.append(f"catchError:{exc}")
        finally:
            trace.append("whenComplete")
        return trace

    expected = {
        "ok_chain": [
            "开始请求...",
            "then1:来自 https://mbsky.com/api 的数据",
            "then2:处理后的: 来自 https://mbsky.com/api 的数据",
            "whenComplete",
        ],
        "err_chain": [
            "开始请求...",
            "catchError:URL 不能为空",
            "whenComplete",
        ],
    }
    actual = {
        "ok_chain": run_chain("https://mbsky.com/api"),
        "err_chain": run_chain(""),
    }
    return {
        "name": "then_catcherror_whencomplete_chain",
        "summary": "校验 Future 的 then/catchError/whenComplete 链式传播与终态清理语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_async_try_on_catch_error_handling():
    class HttpException(Exception):
        pass

    async def fetch_user_profile(user_id: int) -> str:
        await asyncio.sleep(0)
        if user_id <= 0:
            raise ValueError(f"无效的用户 ID: {user_id}")
        if user_id == 404:
            raise HttpException("用户不存在")
        return f"用户 {user_id} 的个人资料"

    async def load_user_profile(user_id: int) -> list[str]:
        events = []
        try:
            profile = await fetch_user_profile(user_id)
            events.append(f"ok:{profile}")
        except HttpException as e:
            events.append(f"http_err:{e}")
        except Exception as e:
            events.append(f"gen_err:{e}")
        finally:
            events.append("finally")
        return events

    async def run():
        return {
            "id_1": await load_user_profile(1),
            "id_404": await load_user_profile(404),
            "id_neg": await load_user_profile(-1),
        }

    actual = asyncio.run(run())
    expected = {
        "id_1": ["ok:用户 1 的个人资料", "finally"],
        "id_404": ["http_err:用户不存在", "finally"],
        "id_neg": ["gen_err:无效的用户 ID: -1", "finally"],
    }
    return {
        "name": "async_try_on_catch_error_handling",
        "summary": "校验 async/await 中异常自动包装进 Future 并由 try/on/catch/finally 分类捕获",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_sync_blocking_vs_async_event_loop(),
        case_future_states_and_async_await_parallel(),
        case_then_catcherror_whencomplete_chain(),
        case_async_try_on_catch_error_handling(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。

入口文件:projects/dart-async-lab/explore-async.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-async.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Dart

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2533.zip

下载课程关联工程包:Dart

课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a2534.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习