Running tasks in sequence inside an infinite loop [closed]

假装没事ソ 提交于 2019-12-14 04:01:09

问题


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

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

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.

Thanks!


回答1:


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());
    }
}

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());
}

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();
    }
}



回答2:


You can wait for the task to complete before starting the next iteration of while loop.

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

Without task.Wait() (or a similar mechanism) the tasks will be scheduled to run, but the next iteration of while loop will begin without waiting for these tasks to complete.




回答3:


You can do something as follows:

List<Task> tasks = new List<Task>();

for (int i = 0; i < 10; i++) //your loop
{
    var task = Task.Factory.StartNew(() => DoWork1()).ContinueWith((t1) => DoWork2()).ContinueWith(t2 => DoWork3());
    tasks.Add(task);
}

Task.WaitAll(tasks.ToArray());


来源:https://stackoverflow.com/questions/49043126/running-tasks-in-sequence-inside-an-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!