Yich Lin
Yich Lin

Reputation: 435

C# console app - Run Task continuous loop

I create multiple task with while loop in console application.
Select and update record from database.
My program will only execute once then close the window.
How to keep console window open,and run task infinitely.

static void Main(string[] args)
{
    Task.Run(async () =>  // <- marked async
    {
        while (true)
        {
            InsertProcess(GameList.RO1);
            await Task.Delay(5000);
        }
    });
    Task.Run(async () =>  // <- marked async
    {
        while (true)
        {
            InsertProcess(GameList.ROS);
            await Task.Delay(5000);
        }
    });
}

public static void InsertProcess(Game game)
{
    using (SqlConnection conn = new SqlConnection(RO1DBConn))
    {
        // ... query database
    }
}

Upvotes: 0

Views: 2719

Answers (1)

Ctznkane525
Ctznkane525

Reputation: 7465

Each Task.Run returns a task object. You have to collect those references, and wait for both tasks to complete using the Task.WaitAll method. WaitAll waits on an array of task records.

Task task1 = Task.Run(async () =>  // <- marked async
{
    while (true)
    {
        InsertProcess(GameList.RO1);
        await Task.Delay(5000);
    }
});
Task task2 = Task.Run(async () =>  // <- marked async
{
    while (true)
    {
        InsertProcess(GameList.ROS);
        await Task.Delay(5000);
    }
});

Task.WaitAll(new []{task1, task2});

Upvotes: 5

Related Questions