Skip to main content

task_suspend

Function task_suspend 

Source
pub async fn task_suspend()
Expand description

主动挂起当前异步任务,直到外部调用Runtime::task_resume后才能唤醒.

task_suspend/Runtime::task_resume的关系类似wait_event/Runtime::notify_events. 只是task_suspend需要结合到task_self使用.

async fn foo(ctx: Rc<RefCell<TaskContext>>) {
    let msg_key = ...;
    non_send_msg(msg_key, ...); // 需要异步等待消息响应
    let task_id = task_self().await;
    ctx.save_key(msg_key, task_id);
    task_suspend().await; // 直到外部调用Runtime::wake(task_id)才返回.
    let resp = ctx.borrow_mut().get_msg_response(msg_key); // 获取响应
    ...
}

fn main() {
    let mut rt = Runtime::new();
    ...
    loop {
        let msg_key = recv_msg();
        if let Some(task_id) = ctx.get_task_id(msg_key) {
            // 唤醒等待msg_key响应的异步任务.
            rt.task_resume(task_id);
        }
        rt.sched();
    }
}