【问题标题】:Why does my program exit even though I spawn a task that should loop forever?为什么我的程序会退出,即使我生成了一个应该永远循环的任务?
【发布时间】:2021-04-02 01:10:05
【问题描述】:

当我在main 中调用do_update().await 时,它会打印出“Foo”,但循环似乎停止了,而不是阻止程序返回。这是什么原因?

async fn do_update() {
    task::spawn(async {
        let duration = Duration::from_millis(10);
        let mut stream = tokio::time::interval(duration);
        stream.tick().await;
        loop {
            println!("Foo");
            stream.tick().await;
        }
    });
}

【问题讨论】:

标签: asynchronous rust task


【解决方案1】:

问题是你需要将任务存储在一个变量中并在其上调用.await

async fn do_update() {
    // here we store it.
    let task = task::spawn(async {
        let duration = Duration::from_millis(10);
        let mut stream = tokio::time::interval(duration);
        stream.tick().await;
        loop {
            println!("Foo");
            stream.tick().await;
        }
    });
    // and here we await it.
    task.await;
}

否则,您创建了任务,但实际上并未指定在程序终止之前需要解决任务。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 2021-03-20
    • 2018-10-12
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多