在无限循环内依次运行任务 [英] Running tasks in sequence inside an infinite loop

查看:89
本文介绍了在无限循环内依次运行任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个任务是按顺序运行的;一个接一个.

I have a several tasks that are run in sequence; one after the other.

Task.Factory.StartNew(() => DoWork1())
            .ContinueWith((t1) => DoWork2())
            .ContinueWith(t2 => DoWork3());

我想将其放入循环中,以便它们无限期地运行(完成DoWork3()之后,返回到DoWork1().我尝试将其放入while循环中,但是一旦任务完成,该循环将进入下一次迭代被启动,创建了许多新任务.

I want to put this inside a loop so they run indefinitely (After DoWork3() is done, go back to DoWork1(). I tried putting inside a while loop, but the loop goes to the next iteration as soon the task is launched, creating a boatload of new tasks.

如果有一种方法可以退出条件以退出循环,或者传递取消令牌,也将很高兴.

Would also be nice to have a way to exit condition to break out of the loop, maybe pass a cancellation token.

谢谢!

推荐答案

最简单的方法是使用async/await:

The simplest way would be to use async/await:

async void DoStuff()
{
    while (true)
    {
        await Task.Factory.StartNew(() => DoWork1())
            .ContinueWith((t1) => DoWork2())
            .ContinueWith(t2 => DoWork3());
    }
}

或者您可以在最后一个任务完成之后再次模拟while(true)来调用该方法:

Or you can call the method again after the last task is completed, simulating a while(true) :

void DoStuff()
{
    Task.Factory.StartNew(() => DoWork1())
        .ContinueWith((t1) => DoWork2())
        .ContinueWith(t2 => DoWork3())
        .ContinueWith(t3=> DoStuff());
}

您也可以Wait显式地执行任务,但这会阻塞正在执行的线程:

You could also Wait for the task explicitly, but this will block the thread you are executing on:

void DoStuff()
{
    while (true)
    {
        Task.Factory.StartNew(() => DoWork1())
            .ContinueWith((t1) => DoWork2())
            .ContinueWith(t2 => DoWork3())
            .Wait();
    }
}

这篇关于在无限循环内依次运行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆