Implementing background tasks in .NET Core using the Generic Host.

In NET Core, you can use Generic Host to implement background tasks. Generic Host is a lightweight host introduced in .NET Core 3.0 that can be used to host background tasks or scheduled jobs in an application.

Here is a simple example code demonstrating how to use Generic Host to implement background tasks.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main(string[] args)
    {
        await CreateHostBuilder(args).RunConsoleAsync();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<BackgroundService>();
            });
}

public class BackgroundService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            // 执行后台任务的逻辑
            Console.WriteLine("Running background task...");

            // 等待一段时间
            await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
        }
    }
}

In the example above, we created a BackgroundService class that inherits from the BackgroundService base class, which provides an abstract method ExecuteAsync for executing the logic of background tasks. In the Program.cs file, we registered the BackgroundService service through the ConfigureServices method, and called the RunConsoleAsync method in the Main method to start the background task.

It is important to note that the ExecuteAsync method in BackgroundService is an infinite loop that executes the logic of background tasks in each iteration. You can check if the background task needs to be canceled by calling the stoppingToken.IsCancellationRequested method, and use Task.Delay method to wait for a period of time.

By using the above code, we can implement simple background tasks in .NET Core. For more complex functionality, we can further extend the BackgroundService class and override the necessary methods according to our needs.

bannerAds